Polymorphism and Method overriding Flashcards
Demonstrate that polymorphism requires the first rule (an overridden method must be at least as accessible as the method it is overriding) to be included as part of the java specification !
public class Animal {
public String getName() {
return “Animal”;
}
}
public class Gorilla extends Animal {
protected String getName() { // DOES NOT COMPILE
return “Gorilla”;
}
}
public class ZooKeeper {
public static void main(String[] args) {
Animal animal = new Gorilla();
System.out.println(animal.getName());
}
}
The reference animal.getName() is allowed because the method is public in the Animal class, but due to polymorphism, the Gorilla object itself has been overridden with a less accessible version, not available to the ZooKeeper class.
This creates a contradiction in that the compiler should not allow access to this method, but because it is being referenced as an instance of Animal, it is allowed.
Therefore, Java eliminates this contradiction, thus disallowing
a method from being overridden by a less accessible version of the method.
Same question about the following rule “a subclass cannot declare an overridden method with a new or broader exception than in the super class” !
// Superclass with a method that declares a checked exception class Superclass {
void doSomething() throws IOException { /* Code that may throw IOException*/ } }
Subclass extends Superclass {
@Override
void doSomething() throws Exception { /* Code that may throw FileNotFoundException*/ }
}
void process(Superclass obj) {
try { obj.doSomething(); }
catch (IOException e) { // Handle IOException } }
public static void main(String[] args) {
Subclass sub = new Subclass();
process(sub); // This is valid because Subclass is a Superclass }
}
If an instance of the subclass is passed to a method using a superclass reference
obj.doSomething() calls the overridden doSomething() method in Subclass, which now throws Exception.
The catch (IOException e) block will not catch Exception, because Exception is not a subtype of IOException.
Since Subclass throws Exception, the catch (IOException e) block will not be able to handle this exception.
Same question about the following rule “overridden methods must use covariant return types “ !