just starting to learn java
got a question

public class Test10 { public static void main(String[] args){ Dog parent = new Dog(); Animal me = new Dog(); me.setParent(parent); Dog myParent = me.getParent(); // ОШИБКА, несовместимость типов } } class Animal{ Animal parent; public void setParent(Animal parent) { this.parent = parent; } public Animal getParent() { return parent; } } class Dog extends Animal{ @Override public Dog getParent(){ return (Dog) parent; } } 

Why does an error occur? the variable me, though of type Animal, but stores a reference to an object of class Dog, hence the overridden getParent method must be called, which makes a animal type downcast, and type Dog, and it seemed to me that it should return type Dog

    1 answer 1

    Because it could be like this:

     class Cat extends Animal { @Override public Cat getParent() { return (Cat) parent; } } ... Cat parent = new Cat(); Animal me = new Dog(); me.setParent(parent); Dog myParent = me.getParent(); //и что теперь делать? 

    The Animal.getParent method Animal.getParent not guarantee that Dog will return , which is what the compiler indicates. The compiler in a strongly typed language (Java) checks the type match. That logically there will be a Dog compiler can not check in the general case, t.ch. he does not try.

    • thanks for the answer! strained the convolutions, remembered that I once read about binding, and formulated an answer for myself in such a way, correct where wrong: what type of object is hidden under the variable found out during the program, respectively, before compiling, the compiler sees the Animal Me variable and thinks that we ( !) call the class method Animal, which returns an object of the class Animal. Therefore, the compiler is reinsured and requires an explicit cast like Dog myParent=(Dog) me.getParent() . And if the method does not return the object of the class Dog at all, then the error will occur during the execution, but the code will compile - Den
    • @Den please! It seems you understand everything correctly. - default locale