以父类的变量访问子类对象的成员

以父类的变量访问子类对象的成员

 

以父类声明变量,并将它指向用子类新建的对象。

此时使用此变量可调用  子类中覆盖父类中的成员函数,或子类中没有而父类中有的成员函数

 

用法:

 

利用父类的数组变量来访问子类对象的成员

   (1)先创建父类的数组变量;

   (2)创建子类对象并放入数组,利用数组元素来访问子类的内容。

 

package com;
public class JavaTest {
public static void main(String ar[])
{
	TFather tc = new TChild();
	tc.show();
	System.out.println(tc.num);
	System.out.println(tc.getClass());
	tc.showF();
	//tc.showC();
}
}

class TFather{
	protected int num = 3;
	public TFather(){
	}
	public void show(){
		System.out.println("父类show");
	}
	public void showF(){
		System.out.println("子类没有");
	}
}
class TChild extends TFather{
	protected int num = 4;
	public TChild(){
		
	}
	public void show(){
		System.out.println("子类show");
	}
	public void showC(){
		System.out.println("子类没有");
	}
}

 

结果:

 

子类show
3
class com.TChild
子类没有

 

  执行tc.showC()时会报错,

 

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The method showC() is undefined for the type TFather

	at com.JavaTest.main(JavaTest.java:10)
 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值