Inheritance in Java and Object Types

populationzero :

I'm currently studying a book for the AP CS A exam, specifically the Barron's book for test preparation.

One section of the book refers to two classes, Student and GradStudent, where GradStudent extends Student.

GradStudent has the method getId() while Student does not.

If I were to run the following code:

Student s = new GradStudent()
s.getId()

The book informs me that I would get an error. Why is this? Since I am initializing it as a GradStudent, wouldn't s have access to the method getId()?

Essentially, if I declare a variable as the superclass, and initialize it to the subclass, what happens?

In other words, how do s and g in the following example differ:

Student s = new GradStudent()
GradStudent g = new GradStudent()

EDIT:

I've now understood that s only has access to the methods in the Student class. So what happens if I do the following:

Student s = (new GradStudent().setId(1) )

What happens to the id field? (Assuming it is only present in the GradStudent class) If I casted s to GradStudent again, would it be able to access the same id?

pkpnd :

You get an error because s is declared to be type Student. It doesn't matter that it was instantiated as a new GradStudent(), the compiler only knows what type s was declared as. So basically you can only use s as if it were a Student (you can only use methods defined by the Student class).

If you really need to use .getId(), you have two options. You can declare s as a GradStudent:

GradStudent s = new GradStudent();
System.out.println(s.getId());

Or, you can cast s to GradStudent:

Student s = new GradStudent();
System.out.println(((GradStudent) s).getId());

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=472733&siteId=1