暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

抽象类、接口

羿起小憩 2021-11-08
281

抽象类、接口

1.    含义

区别

抽象类

接口

定义

抽象类是对类(一类事物)的抽象,包括:构造方法、抽象方法、普通方法、常量、变量

对行为的抽象,包含抽象方法(默认public abstract,所以不需要额外添加)和全局常量

使用

子类集成抽象类(extends)

子类实现接口(implements)

关系

抽象类可以实现多个接口

接口不能集成抽象类,但可以继承多个接口

设计模式

模板设计

工厂设计、代理设计

局限

抽象类有单继承的局限

抽象类中增加方法不影响子类;

没有但实现局限;

接口增加方法影响子类

 选择

如果抽象类和接口都可以使用的 话,优先使用接口,因为避免单继承的局限

 

2.     应用场景区别


抽象类

接口

设计

抽象类作为很多子类的父类,是一种模板式设计,如果需要添加新的方法,抽象类作为模板,可以直接添加带具体实现的方法而无需改变子类。

接口作为规范,规范改变(添加行为),遵守规范的子类都必须进行相应的改动

应用

场景

门和警报的例子:将门设计为一个抽象类,包括打开和关闭两种行为,而将警报设计为一个接口,包括警报行为,进而设计一个警报门继承抽象类并实现警报接口即可

 

interface Alram {

   void alarm();

}

abstract class Door {

   void open();

   void close();

}

class AlarmDoor extends Door implements Alarm {

   void oepn() {

   }

   void close() {

   }

   void alarm() {

   }

}

原文链接:https://blog.csdn.net/Luomingkui1109/article/details/79854634

 

 

3.    抽象方法

ABSTRACT METHOD in Java, is a method that has just the method definition but does not contain implementation. A method without a body is known as an Abstract Method. It must be declared in an abstract class. The abstract method will never be final because the abstract class must implement all the abstract methods.

·      Abstract methods don’t have body, they just have method signature as shown above.

·      If a class has an abstract method it should be declared abstract, the vice versa is not true, which means an abstract class doesn’t need to have an abstract method compulsory.

·      If a regular class extends an abstract class, then the class must have to implement all the abstract methods of abstract parent class or it has to be declared abstract as well.


文章转载自羿起小憩,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论