zoukankan      html  css  js  c++  java
  • 接口和抽象类

    1. 抽象类的实例化

     1 package interfaces;
     2 abstract class BaseWithPrint {
     3   public BaseWithPrint() { print(); }
     4   public abstract void print();
     5 }
    
     6 class DerivedWithPrint extends BaseWithPrint {
     7   int i = 47;
     8   public void print() {
     9     System.out.println("i = " + i);
    10   }
    11 }
    
    12 public class E03_Initialization {
    13   public static void main(String args[]) {
    14   DerivedWithPrint dp = new DerivedWithPrint();
    15   dp.print();
    16   }
    17 } 
    
    /* Output:
    18 i = 0
    19 i = 47

     执行顺序:由于DerivedWithPrint继承自BaseWithPrint,在实例化的过程中,先实例化了基类,基类的构造函数中调用了print,值得注意的是,这边基类中调用的是子类的print函数去执行,然后再执行了dp.print().

    抽象类初始化顺序:父类静态块初始化---->子类静态块初始化---->父类非静态块初始化---->父类构造方法---->子类非静态块初始化---->子类构造方法(先静后动,先父后子)。

    抽象类实际上是定义了一个标准和规范,等着他的子类们去实现,譬如动物这个抽象类里定义了一个发出声音的抽象方法,它就定义了一个规则,那就是谁要是动物类的子类,谁就要去实现这个抽象方法。
    • 抽象类可以继承(extends)类,可以继承(extends)抽象类,可以继承(implements)接口。
    • 接口只能继承(extends)接口。

    2. Q:为什么接口中只能有static和final的域?为什么抽象类中只要有一个方法是abstract的,这个类就必须是abstract的?

       A: 其实两个问题都是因为实例化。

      1.

    Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.

      2. 这是因为抽象方法没有定义方法的实现部分,如果不声明为抽象类,这个类将可以生成对象,这时当用户调用抽象方法时,程序就不知道如何处理了。

  • 相关阅读:
    144环形链表
    83. 删除排序链表中的重复元素
    21合并两个有序链表
    PyCharm2020激活破解教程
    Python正课目录
    2条pip命令解决Python项目依赖的导出和导出
    pip离线安装模块
    Python正课149 —— luffy项目 User表的配置
    Python正课148 —— luffy项目 数据库配置
    解决:django中LookupError No installed app with label 'admin'
  • 原文地址:https://www.cnblogs.com/clara/p/2672095.html
Copyright © 2011-2022 走看看