0

why?

class A { void display() { System.out.print("ghosh"); } } class Refer extends A { public static void main(String args[]) { A r=new Refer(); r.show(); } void show() { System.out.print("somnath"); } } 2. class A { void display() { System.out.print("ghosh"); } } class Refer extends A { public static void main(String args[]) { A r=new Refer(); r.display(); } void display() { System.out.print("somnath"); } } why 1st program is not working , 2nd is working ?

10th Jun 2017, 4:54 AM
Somnath Ghosh
Somnath Ghosh - avatar
1 Answer
+ 2
In the 1st one r is an object of type a, so show() cannot be found. You'd need to write: ((Refer)r).show(); The 2nd one is working since it is 'trying' to call display() in class A but display() in class Refer is Overriding it since r has the value of a Refer object. So display() in class Refer is called. You can use the @Override annotation to make it clearer.
10th Jun 2017, 5:16 AM
Rrestoring faith
Rrestoring faith - avatar