Search code examples
javasubclasssuperclass

type mismatch in java?


I have the below piece of code:

public class AClass {
    public AClass() {
        System.out.println("Constructor A");
    }
}

public class BClass extends AClass{
    public BClass(){
        System.out.println("Constructor B");
    }
}

public class Test {
    public static void main(String[] args) {
        BClass b = new BClass();
    }
}

I changed the code as seen below:

public class AClass {
    public AClass() {
        System.out.println("Constructor A");
    }
}

public class BClass extends AClass{
    public BClass(){
        System.out.println("Constructor B");
    }
}

public class Test {
    public static void main(String[] args) {
        BClass b = new AClass();
    }
}

In the second code snippet, i am getting a type mismatch error for this change BClass b = new AClass(); .

I am learning java and i want to understand the deeper meaning of the error and I want to know why the error in the second code snippet?.


Solution

  • Say you say; a Dog is a type of Animal like

    class Animal { }
    class Dog extends Animal {
        public void bark() { }
    }
    class Cat extends Animal {
        public void meow() { }
    }
    
    Animal a = new Dog(); // is ok.
    

    But you can't say; an Animal is a type of Dog.

    Dog d = new Animal(); // not ok.
    d.bark(); // Animal doesn't have a bark();