shiladitya
shiladitya

Reputation: 2310

Referencing subclasses from superclasses in java

Suppose I have an abstract class Person. There is another class Student which extends Person. But the Student class has a member variable, say college of type String, which is not there in Person class.

We know that we can reference a subclass from a superclass, for example,

Person p = new Student();

Will the object p have the member college?

Upvotes: 2

Views: 192

Answers (2)

Johan Sjöberg
Johan Sjöberg

Reputation: 49237

In your sample, Person object IS a Student and hence will have the college member.

Since you cast the Student to a Person, any public routines or data not present in Person will be hidden by the cast assignment though.

Upvotes: 2

Dan D.
Dan D.

Reputation: 32391

You won't be able to do p.college. However, you can cast it to Student and in this case it will have:

((Student) p).college;

Upvotes: 3

Related Questions