+ 2
What is the output of this code and why?
class A { public void a() { System.out.println("a() of class A"); } } class B extends A { public void a() { System.out.println("a() of class B"); } } class C extends B { public static void main(String ar[]) { C c=new C(); c.a(); } } I know the answer but I want to know how is it decided which a() has to be called?
2 ответов
+ 10
Output should be: a() of class B
Explanation:
- main method calls a() of object c (of class C)
- C class doesn't have any a() method, so it checks its parent class B for a() method
- It gets a() in B, so executes it.
- Why doesn't it checks A? Because a() is an overridden method in B. Since B has its own a(), it doesn't look for a() in A class.
[Method overriding refers to the idea that if child class B contains a method of same prototype as its parent class A, then when the method will be called for child class, the overridden method will be executed, not the base method.]
Note: If C class has its own a() method, it'll call a() of C.
+ 1
Shamima Yasmin thank you :)