Hi friends today I come across that many people stumble on a common question asked in JAVA/Android interview many time.
Problem states that if there is class as A and B and C. B extends A and in class C we have something like
if both class A and B have same method like someMethod(); which method will be called.
Now complete picture is here.
***************************************************************************
Method of A
Method of B
Method of B
That't it copy above program to save as Test.java modify it according your doubt and clear them.
Problem states that if there is class as A and B and C. B extends A and in class C we have something like
A a =new B();B b= new A();
Ok So question is whether above statements are valid or not.
To validate it remember Polymorphism in Java - like biology term species (object) can have many forms - stages.
Means SuperClasses can be initialized with SubClasses. but reverse is not true.
If class B is extending class A, so here class A is superclass and class B is subclass.
Now by this statement
// is valid
A a= new B();
But reverse is not true.
B b= new A(); // will not compile and gives error - incompatible types
now call method ona.someMethod();
if both class A and B have same method like someMethod(); which method will be called.
No doubt class B's method will be called as B's instance is assigned to a.
A a =new B();a.someMethod(); ///calls class B 's method.
Now complete picture is here.
***************************************************************************
import java.util.*;
class Test{
public static void main(String args[]){
Test test=new Test ();
test.run();
}
public void run(){
// Valid class A's object assign to A
A a =new A();
// Valid as class B's object assign to B
B b=new B();
// Call display method of class A
a.display();
// Call display method of class B
b.display();
// Valid as object of B class is assign to a
a=new B();
// Here call display method of class B???
a.display();
//??Why because now A a holds object of class B
// Now call to this method? What will Happen
b=new A();
// throws runtime exception "incompatible types - // class A can not be converted to B"
// So this method won't work.
b.display();
// Then why A a =new B(); is valid.
// By the property of polymorphism
}
class A{
public void display(){
System.out.println("Method of A");
}
}
class B extends A{
public void display(){
System.out.println("Method of B");
}
}
}
*****************************OUTPUT**************************************
Method of A
Method of B
Method of B
That't it copy above program to save as Test.java modify it according your doubt and clear them.
No comments:
Post a Comment