一、Father.javajava
package com.ljb.extend; public class Father { public int x = 10; public int fGet() { return x; } }
二、Son.javaspa
package com.ljb.extend; public class Son extends Father { // 不能出現與父類同名屬性 public int a = 100; public int fGet() { System.out.println(sGet()); return a; } public int sGet () { return x; } /** * @param args * 比如代理模式 * 父類的引用指向子類的對象(自己是父類,使用父類屬性,調用子類覆蓋父類的方法,不能直接訪問子類方法,經過此方法間接訪問) * 只能調用子類覆蓋父類的方法, * 在此重寫方法中能夠調用子類的方法 * 經過此重寫方法能夠訪問到子類的全部方法及屬性 */ public static void main(String[] args) { Father s = new Son(); System.out.println(s.fGet()); // 不能直接調用子類方法 // System.out.println(s.sGet()); } }
三、Sun.java代理
package com.ljb.extend; public class Sun extends Son { public int s = 200; public int fGet() { System.out.println(sGet()); System.out.println(a); return s; } /** * @param args */ public static void main(String[] args) { Father sun = new Sun(); System.out.println(sun.fGet()); } }
四、SecondSon.javacode
package com.ljb.extend; public class SecondSon extends Father { private Son son; // 實現調用第一個子類方法 public int fGet () { if (son == null) { son = new Son(); } return son.a; } /** * @param args */ public static void main(String[] args) { Father f = new SecondSon(); System.out.println(f.fGet()); } }