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?
GradStudent gs = (GradStudent) s; gs.getId()GradStudent, wouldn't s have access to the methodgetId()?" - No, it would not. You see it as aStudent, therefore you can only see what aStudenthas. The terms you are looking for are most probably "static type" and "dynamic type".GradStudentvariable with some variables present only in theGradStudentclass, what would happen if I casted it to aStudent?Animal aand assigned it, at random, eitherBird,Dog, orCat. You would not be able to safely calla.fly()ora.bark()in this case, because you only know you have an Animal, and not what type it is, without inferring and casting to it.setIdreturn? With your latest update, I'm guessing that code would not even compile, unlesssetIdreturnsthis.