I have an interface (move) that should move some shapes.
interface Move { move(); }
abstract class Shape : Move
class Circle : Shape
class Square : Shape
class Triangle : Shape
My doubt is, I must have an interface which moves Shapes but only Circle and Triangle should be able to be moved, so how do I "remove" the interface from Square? Should I remove the interface from Shape and add it manually on Circle and Triangle? I'm kinda confused with this. Hope someone can help me out.
Interface can't provide the implementation of an abstract class. Inheritance vs Abstraction: A Java interface can be implemented using the keyword “implements” and an abstract class can be extended using the keyword “extends”.
In Java, abstract means that the class can still be extended by other classes but that it can never be instantiated (turned into an object).
Interfaces cannot have instance variables and method implementations(except default methods) which is not the case for abstract classes. A class can implement multiple interfaces but can only extend one class regardless of abstraction.
Subclasses use extends keyword to extend an abstract class and they need to provide implementation of all the declared methods in the abstract class unless the subclass is also an abstract class whereas subclasses use implements keyword to implement interfaces and should provide implementation for all the methods ...
You should setup your classes like this:
interface IMovable { move(); }
abstract class Shape : { }
class Circle : Shape, IMovable { }
class Square : Shape { }
class Triangle : Shape, IMovable { }
If not every shape can be moved then Shape
must not implement the interface. Also note I renamed your interface to IMovable
, it's not a huge deal but it's more accepted and a better naming convention.
You can't remove an interface from an inheritance tree.
What you model appears to need two abstract classes - Shape
and MovableShape
.
interface IMove { move(); }
abstract class Shape : {}
abstract class MovableShape : IMove, Shape {}
class Circle : MovableShape{}
class Square : Shape{}
class Triangle : MovableShape{}
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