父类的引用指向子类的对象

一、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());
 }
}
相关文章
相关标签/搜索