Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training

Why it's not wrong if I was replaced by A and wrong if we replace I by B .Can you explain this

The given class structure is like this:


interface I { }
class A implements I { }
class B extends A { }


Would this statement compile?

A obj = new A();


Would this statement compile?

B obj = new A();


What do you think?

Hi,


From my understanding


A obj = new A();


compile without error


B obj = new A();

Throws a compile time error bcoz A is not B .


A obj = new B();

This works bcoz B is a A.

Perfect! Since A implements I, we can further extend it like this:


I obj = new A(); // compiles
A obj = new A(); // compiles
B obj = new A(); // does not compile


When it comes to arrays, the hierarchy remains the same:


I[] obj = new A[]{...}; // compiles
A[] obj = new A[]{...}; // compiles
B[] obj = new A[]{...}; // does not compile


So, as you can see above, when I is replaced with A it works, and when it is replaced with B it does NOT work - which answers the question you have asked.

ExamLab © 2008 - 2024