TechnocratSid
TechnocratSid

Reputation: 2415

Why can't we have current class reference holding the super class object?

Lets say If there are two classes A and B, where A extends B so by convention A can access B's members which are not private. So why can't we create an object of B and assign that reference to A.

Class A:

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

Class B:

public class B { 

}

My main question is :

  1. Why A a = new B(); is incorrect?
  2. Why B b = new A(); is correct?

Upvotes: 1

Views: 80

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075785

So why can't we create an object of B and assign that reference to A.

1) Why A a = new B(); is incorrect?

Because A also (potentially) has features B doesn't have, so the instance (which is a B) isn't an A, so you can't assign a B instance to an A-typed variable.

2) Why B b = new A(); is correct?

Because instances of A are B instances, they just may also be a bit more than B instances. So it's fine (and common) for a B-typed variable to refer to an A instance. Remember, inheritance is an "is a" relationship. A extends B means an A instance is a B instance.

Let's use more meaningful class names and include some state:

class Super {
    private int foo;
    // ...details omitted...
}

class Sub extends Super {
    private int bar;
    // ...details omitted...
}

So an instance of Super has a data slot for foo:

+−−−−−−−−−−−−−−−−−−+
| (Super instance) |
+−−−−−−−−−−−−−−−−−−+
| foo: 0           |
+−−−−−−−−−−−−−−−−−−+

An instance of Sub has a slot for foo (because it is a Super) and also a slot for bar:

+−−−−−−−−−−−−−−−−−−+
|  (Sub instance)  |
+−−−−−−−−−−−−−−−−−−+
| foo: 0           |
| bar: 0           |
+−−−−−−−−−−−−−−−−−−+

A variable of type Super can refer to a Sub instance; the instance has all the data slots (and behavior, not shown) that a Super has. But a variable of type Sub cannot refer to a Super instance; the instance doesn't have the bar data slot (and potentially Sub-specific behaviors, not shown).

Upvotes: 8

Absent
Absent

Reputation: 914

You cannot assign a superclass instance to a variable because you might run into a situation where you want to e.g. call a method from the subclass.

At compile time and at runtime you would run into the same problem: What shall happen if a method from the subclass is called on the variable of type subclass while it holds a type superclass? The superclass does not necessarily have all fields and methods from the subclass.

The other way it works, because everything the superclass has, the subclass also has.

Upvotes: 0

Related Questions