Accessing fields of a subclass
If you want a method to intake an object of a superclass type, but you want it to do things differently depending on what subclass it is, is it possible to take input as the superclass, and then refer to fields of the subclass within that method?
So if i wanted to take an object of type shape, but depending on what shape it might be I want to do things differently... like a circle has a radius,but a rectangle doesnt.
ie.. (This is a very dodgy pseudo code type explanation of what I want to do..)
public void method(Superclass object) {
if (object type Subclass)
do this and refer to fields in subclass
else if (object type Subclass 2)
do this and refer to fields in subclass...
etc...
}
I really want to stick with the input being of the superclass type. Is this possible?
Re: Accessing fields of a subclass
Nevermind. I ended up writing the method for each subclass, and defining it as being an abstract method in the super class. This way I could refer to the method using an object from the superclass as input, and still have it do different things depending on what subclass it was.
Re: Accessing fields of a subclass
In regards to your "very dodgy pseudo code" you would need to use the instanceof operator and then cast the object to the subclass.
Re: Accessing fields of a subclass
The code which you have provided doesn't work at all coz you want to access subclass related thing with Superclass reference. It will directly give you compile time error if it is not in super class. You need to have the same method in in subclass with super class.