Calling a subclass method from superclass

When you declare a variable as having the type of the superclass, you can only access (public) methods and member variables of the superclass through that variable.

Pet cat = new Cat("Feline",12,"Orange"); 
cat.getName(); // this is OK
cat.getColor(); // this is not OK, getColor() is not in Pet

To access the methods in the concrete class (Cat in this case), you need to either declare the variable as the derived class

Cat cat = new Cat("Feline",12,"Orange"); 
cat.getName(); // OK, getName() is part of Cat (and the superclass)
cat.getColor(); // OK, getColor() is part of Cat

Or cast it to a type you know/suspect is the concrete type

Pet cat = new Cat("Feline",12,"Orange"); 
((Cat)cat).getName(); // OK (same as above)
((Cat)cat).getColor(); // now we are looking at cat through the glass of Cat

You can even combine the two methods:

Pet pet = new Cat("Feline",12,"Orange"); 
Cat cat = (Cat)pet;
cat.getName(); // OK
cat.getColor(); // OK

Leave a Comment