javaclassinheritance

Why B b = new A() is invalid and A a = new B() is valid when B extends A?


I am new to JAVA and want to know that why

A a = new B();

is valid and

B b = new A();

is invalid Considering that:

class A;
class B extends A;

Solution

  • Because B, by extending A, is also an A. We say this in object-orientation terms by saying that a B is-a A. This means that you can use a B anywhere you use an A.

    This relationship is not commutative -- B is-a A does not imply that A is-a B. Therefore you cannot use an A anywhere you would use a B.

    Consider this case:

    class Animal;
    class Dog extends Animal;
    

    This makes sense:

    Animal animal = new Dog();
    

    Anywhere it makes sense to use an Animal you can also use a Dog. This is intuitive.

    Dog dog = new Animal();
    

    This, on the other hand, does not make sense.