java继承中的覆盖与隐藏区别

   java 继承隐藏与覆盖:

1)子类只能覆盖父类非静态方法;且只能隐藏父类的同名变量和静态方法。

 

覆盖:调用的总是实例化对象的同名方法;

隐藏:调用的总是引用的类型的同名方法或同名变量;

 

2)代码实例:

public class A {

    public int i=0;

    public void hello(){
        System.out.println("this is A");
    }

    public  static void staticTtest(){
        System.out.println("A's static");
    }
}
 
 
 
public class B extends A{ 
public int i=1; //隐藏 
public void hello(){
 System.out.println("this is B"); //覆盖 
} 
public static void staticTtest(){ //隐藏  
System.out.println("B's static"); 
} 
}
public class appMain {
 public static void main(String[] args){
    A a=new B(); 
    a.hello(); //非静态方法,故覆盖;输出B的hello方法  
    System.out.println(a.i); //同名变量,故隐藏;A引用类型,故输出A的i变量  
    a.staticTtest(); //同名静态方法,故隐藏;A引用类型,故输出A的staticTtest   
    B b=(B)a; 
    b.hello(); //非静态方法,故覆盖;输出B的hello方法  
    System.out.println(b.i); //同名变量,故隐藏;B引用类型,故输出B的i变量  
    b.staticTtest(); //同名静态方法,故隐藏;B引用类型,故输出B的staticTtest 
 } 
}

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值