When to use an interface instead of an abstract cl

2018-12-31 07:01发布

This may be a generic OOP question. I wanted to do a generic comparison between an interface and an abstract class on the basis of their usage.

When would one want to use an interface and when would one want to use an abstract class?

22条回答
查无此人
2楼-- · 2018-12-31 07:46

in java you can inherit from one (abstract) class to "provide" functionality and you can implement many interfaces to "ensure" functionality

查看更多
像晚风撩人
3楼-- · 2018-12-31 07:48

1.If you are creating something that provides common functionality to unrelated classes, use an interface.

2.If you are creating something for objects that are closely related in a hierarchy, use an abstract class.

查看更多
一个人的天荒地老
4楼-- · 2018-12-31 07:50

When to do what is a very simple thing if you have the concept clear in your mind.

Abstract classes can be Derived whereas Interfaces can be Implemented. There is some difference between the two. When you derive an Abstract class, the relationship between the derived class and the base class is 'is a' relationship. e.g., a Dog is an Animal, a Sheep is an Animal which means that a Derived class is inheriting some properties from the base class.

Whereas for implementation of interfaces, the relationship is "can be". e.g., a Dog can be a spy dog. A dog can be a circus dog. A dog can be a race dog. Which means that you implement certain methods to acquire something.

I hope I am clear.

查看更多
深知你不懂我心
5楼-- · 2018-12-31 07:51

My two cents:

An interface basically defines a contract, that any implementing class must adhere to(implement the interface members). It does not contain any code.

On the other hand, an abstract class can contain code, and there might be some methods marked as abstract which an inheriting class must implement.

The rare situations I've used abstract classes is when i have some default functionality that the inheriting class might not be interesting in overriding, in say an abstract base class, that some specialized classes inherit from.

Example(a very rudimentary one!):Consider a base class called Customer which has abstract methods like CalculatePayment(), CalculateRewardPoints() and some non-abstract methods like GetName(), SavePaymentDetails().

Specialized classes like RegularCustomer and GoldCustomer will inherit from the Customer base class and implement their own CalculatePayment() and CalculateRewardPoints() method logic, but re-use the GetName() and SavePaymentDetails() methods.

You can add more functionality to an abstract class(non abstract methods that is) without affecting child classes which were using an older version. Whereas adding methods to an interface would affect all classes implementing it as they would now need to implement the newly added interface members.

An abstract class with all abstract members would be similar to an interface.

查看更多
登录 后发表回答