Why can I call: 1)

Human human = new Student(); human.run(); 

2)

 Student student = new Human(); student.run(); 

I understand that the second example will not start, I can not explain why. Explain, please.

    1 answer 1

    Probably, Student inherited from Human . Those. class declaration looks something like this:

     public class Student extends Human { .... } 

    Those. a student is a special case of a person. Obviously, all students are people, but people are not necessarily students.

    In the first example, you declare a variable of the abstract (wider) type Human and assign it to the created object of a concrete (narrower) type Student'. Т.е. мы получаем человека, о котором также известно, что он студент, но в контексте переменной Student'. Т.е. мы получаем человека, о котором также известно, что он студент, но в контексте переменной Student'. Т.е. мы получаем человека, о котором также известно, что он студент, но в контексте переменной human` we don’t know about it.

    In the second example, a variable of the type Student declared and we can assign a value of the same or a narrower type to it. Imagine that the Human class has a field with the last name and the run method, and the Student class has a field with the name of the university and the study method. If the assignment in the second example were possible, what would we get when calling the study method? After all, a variable is assigned an object of the Human type and there is no study method in it.

    Therefore, you can assign only an object of the same or a child type to a variable. But not the parent.

    • thanks, it came) - Stee1House