Java Reference
In-Depth Information
redefine it my way, without affecting your print() method in any way. You can keep using your print() method.”
If a class overrides a method, it affects the overriding class and its subclasses. Consider the following declaration
of class C :
public class C extends B {
// Inherits B.print()
}
Class C does not declare any methods. What method does class C inherit: A.print() or B.print() , or both? It
inherits the print() method from class B . A class always inherits what is available from its immediate superclass
(declared in superclass or inherited by its super superclass). If a class D inherits from class C , it will inherit print()
method of class B through class C .
public class D extends C {
// Inherits B.print() through C
}
Let's consider two more classes E and F , which inherit from D and E , respectively. Class E overrides the print()
method of class B , which it inherited from class D .
public class E extends D {
public void print() {
System.out.println("E");
}
}
public class F extends E {
// Inherits E.print() through E
}
What will be the output of the following snippet of code?
A a = new A();
a.print(); // will print A
a = new B();
a.print(); // will print B
a = new C();
a.print(); // will print B
a = new D();
a.print(); // will print B
a = new E();
a.print(); // will print E
a = new F();
a.print(); // will print E
The comments in the code tell you what will be printed. Can you figure out why you get this output? There are
three things at work. First, you can assign an object of a descendant of class A to a variable of class A type. This is the
reason that you have called a.print() in all statements. Second, the print() method has been overridden by some
of the descendants of class A in the class hierarchy. Third, late binding performs the magic of calling the appropriate
print() method depending on the class of the object to which the variable is referring to at runtime.
 
Search WWH ::




Custom Search