0
class A {

}

class B extends A {

   public static void main(String args[]) {
      B b = new A();
   }

}

Why does this throw a compile time error? to suppress the compile time error we can do B b=(B)new A(); but then also it will through ClassCastException.

3
  • 6
    Because instance of A is not B Commented Sep 8, 2014 at 12:43
  • "through compile time error" or "throws compile time error"? Commented Sep 8, 2014 at 12:43
  • b is an instance of B, not A. It will only work if you use a parent type variable and assign it a Derived type: A a = new B(); This is how inheritance works. Commented Sep 8, 2014 at 12:44

4 Answers 4

4

B is-a A, but A is not a B.

You can only assign an object to an instance of itself or it's super classes, not it's subclasses.

Sign up to request clarification or add additional context in comments.

Comments

1

B b=new A() -> because you cant reference a super type instance with a subtype reference.

B b=(B)new A() -> Yes you can downcaste it to B as A and B are in inheritance hierarchy. But at runtime since A is a super type you cant caste it B.

In the case of B b=(B)new A(), compilation goes successful because for down casting, compiler checks if types are related (i.e. inheritance) but at runtime, you are trying to refer a super type object (object of A) with Subtype reference(B), so you end up with exception.

Comments

0

You cannot instantiate a father class to the inherited ones because not all the members from the inherited will have the opportunity to be initialized.

You can, however, do the opposite: A a = new B(); because A being father is a generalization of B and all its members had the opportunity to be initialized.

Comments

0

According to Dynamic method dispatch, your superclass's object reference can point to the objects of its subclasses but vice versa is not valid(that is subclass object reference cannot be made to point to the Super class object). In your code A is the super class and hence can point to itself and B's object as B is extending A. However on doing B b=(B)new A(); you are perfoming a downcaste.Best explaination is here: Class casting in java enter image description here

Here if you consider all of the above as classes and circle,square and triangle are the classes extending class shape than it makes sense that object reference of shape can point to the objects of the circle,square and triangle,however the three classes can never point to the object of shape class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.