I have a class called Shape that is abstract, and a class named Circle that extends Shape
Shape shapeCircle = new Circle();
I can set and get colors of shapeCircle fine because the color getters and setters are in Shape , but the dimensions of Circle is only for the Circle class (radius).
If Circle class has an instance variable private int radius and a method called getRadius(), how can I get/set the radius of shapeCircle? I tried shapeCircle.getRadius();, but no luck.
Here the reference is of Shape and shape class doesn’t defines radius variable.So you cannot use
shapeCircle.getRadius();To invoke get/set radious method type cast the shapecircle variable like this
Now you can invoke the get/set radious methods. Please note that typecasting code should be in some different method to benefit using polymorphism.
EDIT:
You should design your abstract classes or interfaces to be having all important/common operations/methods which will help you in writing polymorphic code. For example: Radius field is specific to a Circle class.But consider you eventually want to calculate the area. So you should define CalculateArea() method in your abstract class and let every shape implement this method.This way, you achieve polymorphism.
Point is don’t confine yourself with the radius example.Try to define classes in a way so that you can benefit from polymorphism.