Reputation: 75
We know that class A extends Object class implicitly but if we instantiate Object class object with class A constructor and try to access print() method of class A it shows a compile time error while in other case where class B extends class A and Class A object instantiated with class B constructor and try to access print() method works fine.
class A{
public void print(){
System.out.println("A");
}
}
class B extends A{
public void print(){
System.out.println("B");
}
}
public class MyClass {
public static void main(String args[]) {
Object o = new A();
o.print(); // error
A a = new B();
a.print(); // print B
}
}
Upvotes: 0
Views: 59
Reputation: 140613
This line:
o.print(); // error
You know that o
is actually of type A
.
The compiler could know, but in Java, it does not know. The compiler only knows that there is some variable named o
, of type Object
.
Thus the compiler slaps your fingers for invoking a method on o
that the declared type Object
doesn't support!
Other languages are "smarter" about such things, but in Java, that is how things are.
Upvotes: 2
Reputation: 3131
You example with class B extends A isn't the same as the case of A extends Object. The difference is that in the first case the superclass (A
) contains the print()
method, in the second case the superclass (Object
) doesn't contain the print()
. If you remove the print()
method from the A
class, the second part won't work either:
class A{
}
class B extends A{
public void print(){
System.out.println("B");
}
}
public class MyClass {
public static void main(String args[]) {
Object o = new A();
//o.print(); // error
A a = new B();
a.print(); // error
}
}
Upvotes: 1
Reputation: 614
Because Object class does not have print() method and the reference o is of type Object, the compiler will throw an error. In case 2 : class A has print() method thats why no compilation error and at runtime it calls class B's print() method because we assigned class B's reference at runtime.
Upvotes: 0