• java中请给一个Abstract类实现接口的实例!


    2.Abstract类实现接口 

    如果实现某接口的类是abstract类,则它可以不实现该接口所有的方法。但其非abstract的子类中必须拥有所有抽象方法的实在的方法体;(当然它abstract爹的也算作是它的)

    If a class implements an interface, it must implement all of its methods in the interface, otherwise, this class must be an abstract class. if it is an abstract class, it can leave some methods in the interface unimplemented.refer to the following example.

    例1.2---
    interface OpenClose {undefined
        void open();
        void close();
    }
    abstract class Door implements OpenClose {undefined
        public void close() {undefined
            System.out.println("旋转把手,拉!");
        }
    }
    /*AdvancedDoorMark_to_win这个类不需要实现close()。因为它已经有close()。它的close()位置在它的超类"Door"。
    AdvancedDoorMark_to_win does not need to implement close(), because it already has
    close(), the only thing is that the position of its close() is inside its
    super class "Door"
    */
    class AdvancedDoorMark_to_win extends Door {undefined
        public void open() {undefined
            System.out.println("旋转把手,推!");
        }

    }
    public class Test {undefined
        public static void main(String args[]) {undefined
            AdvancedDoorMark_to_win d = new AdvancedDoorMark_to_win();
            d.open();
            d.close();
        }
    }

    java为什么用abstract类实现接口

    抽象类实现接口,抽象类可以不用实现接口的方法,同时可以在抽象类中定义抽象的和不抽象的方法;

    子类继承抽象类,必须实现抽象类中的抽象方法和接口定义的全部方法,同时子类可以直接继承父类的非抽象方法,这样继承使用,更加灵活,拓展性更好,代码更少。

    例如:如果要拓展一个子类公用方法,可以直接在父类中添加实现,如果子类实现不同的方法,但是又要遵循统一接口的就可以在接口中定义,如果需要父类定义一个不完整的方法,就可以在父类中定义一个抽象方法,这样看起来,就比较灵活。

    您看,是不是这个理?码农一枚,一起学习!

    假如

    B

    是一个

    抽象类

    A

    是一个

    接口

    那么,我想你是想问这句话

    abstract class B implements A

    吧。

    被abstract修饰

    B

    的是一个抽象类,因此,他不用实现

    A

    申明的所有接口,他等着他的子类去实现,因此,这样做的好处是,子类可以专注自己的逻辑。而统一需要处理的事情可以在

    B

    中去做。

    java8 引入了 default方法,可以减少abstract类的编写,但是仅限方法变量调用,涉及到类变量调用还得 定义统一抽象类。

  • 相关阅读:
    工具推荐-根据IP地址精确定位经纬度(永久免费)
    VMware与Centos系统安装
    Python 之ConfigParser模块
    Python记录日志模块推荐-loguru!
    Excel 两列单元格合并超级链接的VBA 写法
    Shell脚本日志关键字监控+告警
    Python字符串及基本操作(入门必看)!!
    github release 下载文件慢、或者失败的解决方法
    Python字典及基本操作(超级详细)
    为什么使用 Containjs 模块化管理工具效率高?
  • 原文地址:https://www.cnblogs.com/ExMan/p/15999267.html
Copyright © 2020-2023  润新知