Reputation: 207
I have three classes naming A , B and Test class and each class has three methods as in the below code. Now from the Test class I am creating an object of B class and putting it in A which is the parent class. Now the method of A is not getting invoked but method of B is getting invoked , why? Also when I make the methods as static then the method of A class gets invoked. What is the reason behind this?
class A {
void test1() {
System.out.println("hello");
}
}
class B extends A {
void test1() {
System.out.println("From B class");
}
}
class Test extends B{
public static void main(String args[]){
A obj=new B();
obj.test1();
}
public void test1(){
System.out.println("from Test class");
}
}
Upvotes: 2
Views: 1660
Reputation: 357
In your class definitions method test1 () in child class (i.e. B) overrides the method defined in parent class (i.e. A)
The code below creates an object instance of B using reference of type 'A'
A obj = new B();
All non-static methods will be called on actual instance (i. e. of Class B)
All static methods will be called on reference hence it will refer to Class A. Static methods cannot be overridden.
Upvotes: 1
Reputation: 121
The first case is related to dynamic(or late) binding. The compiler figures out the object type in runtime, so in runtime the certain method of the certain object will be chosen to be called. The second case is related to static(or early) binding. The compiler knows that the static method couldn't be overridden, so it could be binded at the compile time. As the static method related to its class but not to the certain instance of this class, the method of this class(in your case it is A) will be called.
Upvotes: 0
Reputation: 4460
At Runtime, the overridden method will be called. Static methods cannot be overridden, instead you can hide the parent implementation from the child class.
This will NOT depend on the reference type.
A obj = new B();
obj.test1();//Method on B will be invoked.
B obj = new B();
obj.test1();//Still method on B will be invoked.Because at runtime we have B obj
Because : You have provided specific implementation for your test
method in B
type of objects. Please read about Polymorphism.
Upvotes: 0
Reputation: 11
because you are overwrite the method , fron A with B, you need investigates polymorphism
Upvotes: 0
Reputation: 17605
The behaviour you describe is exactly how it is supposed to be in Java, where a method is virtual by default. The access on the instance of B
you use depends on the actual type of the value referenced by obj
(which is B
), not the type of the reference obj
as declared (which is A
). If the methods are made static, the specific class is referenced.
Upvotes: 0