Skip to main content

Posts

Showing posts with the label Polymorphism

Why it is not required to declare the exceptions declared in the superclass' method when overriding it?

-- An implementation of a overriding method in a subclass may be totally different with its overridden method in the superclass. It may not have any exceptions needed to throw at all. The only restriction in Java compiler ( 8.4.6 Method Throws )is that the overriding method in subclass cannot be declared to throw border or new checked exceptions than the overridden method in the superclass (otherwise, you may break other codes because the runtime polymorphism).

What is runtime polymorphism in Java?

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementation. This is one of the basic principles of object oriented programming. The method overriding is an example of runtime polymorphism. You can have a method in subclass overrides the method in its super classes with the same name and signature. Java virtual machine determines the proper method to call at the runtime, not at the compile time. Let's take a look at the following example:   class Animal { void whoAmI() { System.out.println("I am a generic Animal."); } } class Dog extends Animal { void whoAmI() { System.out.println("I am a Dog."); } } class Cow extends Animal { void whoAmI() { System.out.println("I am a Cow."); } }

What is runtime polymorphism in Java?

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementation. This is one of the basic principles of object oriented programming.   The method overriding is an example of runtime polymorphism. You can have a method in subclass overrides the method in its super classes with the same name and signature. Java virtual machine determines the proper method to call at the runtime, not at the compile time.   Let's take a look at the following example: class Animal { void whoAmI() { System.out.println("I am a generic Animal."); } } class Dog extends Animal { void whoAmI() { System.out.println("I am a Dog."); } } class Cow extends Animal { void whoAmI() { System.out.println("I am a Cow."); } } class Snake extends Animal { void whoAmI() { System.out.println("I am a Snake....