Java-Initialization
程序员文章站
2022-03-30 16:49:06
1 package interfaces.music; 2 abstract class Base{ 3 Base(){ 4 print(); 5 } 6 public abstract void print(); 7 } 8 class Derived extends Base{ 9 privat ......
1 package interfaces.music; 2 abstract class base{ 3 base(){ 4 print(); 5 } 6 public abstract void print(); 7 } 8 class derived extends base{ 9 private int i = 1; 10 public void print() { 11 system.out.println(i); 12 } 13 } 14 public class e03_initialization { 15 public static void main(string[] args) { 16 derived d = new derived(); 17 d.print(); 18 } 19 }
首先寻找main函数,进入main函数;
执行 derived d = new derived();
加载 class derived extends base,发现有一个父类;
加载父类base;
父类base有个一构造函数,执行构造函数;
构造函数中有个print方法,此方法被子类print方法覆盖,但此时子类方法中 i=1 未被加载,因此系统默认给 i 赋值为0,故此时会执行子类print方法,打印出 0;
加载子类derived;
执行d.print,打印出 1;
上一篇: 新品种青枣本身的奥秘