继承和多态性 -- 方法和变量的覆盖和隐藏


隐藏: 子类在继承父类的时候,会隐藏父类的变量(不管是静态变量还是实例变量)和父类的static静态方法。此时,子类不能访问父类的方法和变量,但是如果将子类强制转换为父类,则可以访问父类隐藏的变量(不管是静态变量还是实例变量)和static静态方法。

覆盖:子类中继承父类的时候,会覆盖父类的实例方法。此时,子类不能访问父类的方法和变量,但是如果将子类强制转换为父类,还是不能访问父类被覆盖的实例方法。这个是实现多态性的关键。


实例变量:是指被声明在类而不是方法里面的,实例变量存在于所属的对象中。

class Inherit_Parent{
	int x = 1 ;
	static int y = 2;
	int z = 3;
	public Inherit_Parent() {
		super();
	}
	
	public void func(){
		
		System.out.println("父类func(x)方法 -- x = "+ x + " y = "+ y + " z="+z);	
	}
	
	public static void func_static(){
		
		System.out.println("父类func_static(x)方法: ");	
	}
	
}

public class Inherit_Child extends Inherit_Parent {

	int x = 4 ;
	static int y = 5;
	int z = 6;
	
	public Inherit_Child() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public void func(){
		
		System.out.println("子类func(x)方法 -- x = "+ x + " y = "+ y + " z="+z);	
	}
	
	public static void func_static(){
		
		System.out.println("子类func_static(x)方法: ");	
	}
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Inherit_Child child1 = new Inherit_Child();
		System.out.println("child1: x = "+child1. x + " y = "+child1. y + " z="+ child1.z);	
		child1.func();
		child1.func_static();
		
		Inherit_Parent parent2 =(Inherit_Parent) child1;
		System.out.println("parent2: x = "+parent2. x + " y = "+parent2. y + " z="+ parent2.z);	
		parent2.func();
		parent2.func_static();
	}

}


打印出来的log为:

child1: x = 4 y = 5 z=6
子类func(x)方法 -- x = 4 y = 5 z=6
子类func_static(x)方法: 
parent2: x = 1 y = 2 z=3
子类func(x)方法 -- x = 4 y = 5 z=6
父类func_static(x)方法: 


通过log可以看出,强制将子类child1向上转型为父类parent2,

通过parent2读取的实例变量,仍然是父类的x/y/z(即log:parent2: x = 1 y = 2 z=3)

通过parent2读取的实例方法func(),却是被覆盖了的子类的方法(即log:子类func(x)方法 -- x = 4 y = 5 z=6)。如果要执行父类的方法,那么调用super.func()。

通过parent2读取的静态static方法func_static(),仍然是父类的方法(即log:父类func_static(x)方法: )





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值