I know this is a very simple question, but I have been working in Python for quite a long time and now that I must go back to Java, I seem to have problems changing the chip and wrapping my head around Java's basic polymorphism.
Is it possible to overwrite (implement, to be precise) a class' abstract
method in Java using one of the inherited classes as argument?
Let me explain with a very simple example (following the "almost official" example with shapes)
class Shape {}
class Circle extends Shape {}
class Triangle extends Shape {}
abstract class ShapeDrawer {
abstract void draw(Shape s);
}
class CircleDrawer extends ShapeDrawer {
void draw(Circle c){
System.out.println("Drawing circle");
}
}
Is there any way of having Java identifying the draw
method in the CircleDrawer
class as the implementation of the abstract draw
in ShapeDrawer
? (The Circle
class extends from Shape
after all)
Otherwise put: What I'd like is that the draw
method of the CircleDrawer
class accepts only instances of type Circle
, but at the same time, I'd like to tell the Java compiler that the void draw(Circle c)
is actually the implementation of the abstract method abstract void draw(Shape s)
located in its parent class.
Thank you in advance.
You can solve your problem by means of generics:
public abstract class ShapeDrawer<T extends Shape> {
public abstract void draw(T shape);
}
public class CircleDrawer extends ShapeDrawer<Circle> {
public void draw(Circle circle) { ... }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With