Java抽象类(Abstract Class)与接口(Interface)区别
Posted 海角在眼前
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java抽象类(Abstract Class)与接口(Interface)区别相关的知识,希望对你有一定的参考价值。
抽象类与接口比较
抽象类跟接口类似,都不能实例化,可能包含不需实现方法或已实现的方法。
抽象类可以定义一些不是静态或常量的字段,定义 public, protected, private访问级别的具体方法。
接口的所有字段自动是public、静态、常量,所有定义的方法的访问级别都是public。
类只能继承一个抽象类,可以实现多个接口。
抽象类使用场景
1、你想在几个密切相关的类共享代码。
2、你想让继承你抽象类的类有一些共用的字段或方法,或想设置protected, private的访问级别。
3、你想声明非静态或非常量的字段。这样可以定义访问或修改字段状态的方法。
接口使用场景
1、你想要不相关的类实现你的接口。
2、只想声明特定数据类型的行为,不关注实现的情况。
3、实现多继承效果。
例子
An example of an abstract class in the JDK is AbstractMap, which is part of the Collections Framework. Its subclasses (which include HashMap, TreeMap, and ConcurrentHashMap) share many methods (including get, put, isEmpty, containsKey, and containsValue) that AbstractMap defines.
An example of a class in the JDK that implements several interfaces is HashMap, which implements the interfaces Serializable, Cloneable, and Map<K, V>. By reading this list of interfaces, you can infer that an instance of HashMap (regardless of the developer or company who implemented the class) can be cloned, is serializable (which means that it can be converted into a byte stream; see the sectionSerializable Objects), and has the functionality of a map. In addition, the Map<K, V> interface has been enhanced with many default methods such as merge and forEach that older classes that have implemented this interface do not have to define.
Note that many software libraries use both abstract classes and interfaces; the HashMap class implements several interfaces and also extends the abstract class AbstractMap.
接口能不能有实现的方法?
Java8允许接口有默认方法和静态方法,只不过调用方式不一样,如下。
public interface RdNum { void play(); static int getANum(){ return 123; } default String getAStirng(String str){ return str + "嘤嘤嘤"; } } public class R implements Interface { ...... } public class Test { public static void main(String[] args){ R r = new R(); System.out.println(r.getAStirng("哈哈哈")); System.out.println(RdNum.getANum()); } }
参考文献
https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
以上是关于Java抽象类(Abstract Class)与接口(Interface)区别的主要内容,如果未能解决你的问题,请参考以下文章
Java抽象类(Abstract Class)与接口(Interface)区别
抽象类(abstract class)和接口(interface)Java面试题
抽象类(abstract class)和接口(Interface)的区别