手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Java抽象类(Abstract Class)与接口(Interface)区别

[日期:2018-04-19] 来源:Linux社区  作者:lovesong [字体:大 中 小]

抽象类与接口比较

抽象类跟接口类似,都不能实例化,可能包含不需实现方法或已实现的方法。

抽象类可以定义一些不是静态或常量的字段,定义 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

本文永久更新链接地址:https://www.linuxidc.com/Linux/2018-04/151962.htm

linux
相关资讯       Java接口  Java抽象类 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款