码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-08-05 16:35:46      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

1、Father.java

package com.ljb.extend;
public class Father {
 public int x = 10;
 public int fGet() {
  return x;
 }
}

2、Son.java

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());
 }
}

3、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());
 }
}

4、SecondSon.java

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());
 }
}

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

标签:

原文地址:http://my.oschina.net/u/2320342/blog/488201

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!