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

  • 相关阅读:
    eclipse web项目没有run on server
    npm install 包 失败解决方法
    svn already lock解决方法
    查看centos的版本
    SmartGit 授权Non-Commerical
    http://jingyan.baidu.com/article/dca1fa6fa07000f1a44052f6.html
    http://zhidao.baidu.com/link?url=3tJ_i5gyYLrd7rFPk0eRYre_oxjCZvTOMOutp89LGhUgi6Ic6Ncama_GMAHnwfF73SVYGqy364vDfv6AY4ERPa
    http://www.oschina.net/code/snippet_12_13918
    http://www.360doc.com/content/12/0516/14/1671317_211422841.shtml
    https://v2ex.com/t/170386
  • 原文地址:https://www.cnblogs.com/clara/p/2672095.html
Copyright © 2011-2022 走看看