Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend interface to an abstract class

Tags:

c#

oop

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.

like image 498
sok Avatar asked Oct 01 '12 12:10

sok


People also ask

Can we extend interface to abstract class?

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”.

What does it mean to extend an abstract class?

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).

Can interface extend multiple abstract class?

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.

What is the keyword for extending an interface and abstract class?

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 ...


2 Answers

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.

like image 137
Mike Perrenoud Avatar answered Oct 04 '22 03:10

Mike Perrenoud


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{}
like image 27
Oded Avatar answered Oct 04 '22 03:10

Oded