James James - 1 year ago 55
Java Question

Syntax about declaring a variable using an inherited class

Referring to the top answer in this thread:

What is the main difference between Inheritance and Polymorphism?

We're working under the assumption that Student extends Person.
What does the following syntax mean?

Person p = new Student();

I don't really understand it. If 'p' starts as type Person, why is not a syntax error to have it hold a type 'Student'?

With that in mind, are the following two different at all?

Person p = new Student();
# vs
Student s = new Student();

Do p and s hold the same type of object? Except for the fact that they point to two different objects, is there anything else that is actually different about the two? What's the significance of writing Person or Student as the 'starting type'?

Answer Source

The difference is essentially that a Student is a Person but a Person is not necessarily a Student (even in real life).

If your code is dealing with things a Person needs to do (eat, drink, walk, talk, etc) then you necessarily have to code using Person, since using Student would exclude anyone that wasn't a Student (Teacher for example)

These are different:

Person p = new Student();
# vs
Student s = new Student();


Person p = new Student(); // A Student is a Person ... not an error
Student s = new Student(); // A Student is (obviously) a Student... not an error
Student s = new Person(); // A Person isn't required to be a Student!  ... error!

When calling methods on an object the implementation of a derived class (Student) may override the implementation of the parent class (Person), for example (and this is fairly contrived)

Person {
    boolean getsMuseumDiscounts() { return false; }

Student extends Person {
    boolean getsMuseumDiscounts() { return true; }
    boolean hasSkippedClass() { return true; }

Person p = new Person();
Person s = new Student();
p.getsMuseumDiscounts(); // returns false
s.getsMuseumDiscounts(); // returns true (even though the compiler thinks s is a Person)


Person p = new Student();
# vs
Student s = new Student();
p.hasSkippedClass(); // is an error, Person does not implement this function
s.hasSkippedClass(); // is perfectly fine
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download