Java中static方法的隐藏

package cn.StaticDemo01;

public class BaseClass {
    public void methodOne(){
        System.out.println("The methodOne in BaseClass");
    }
    public void methodTwo(){
        System.out.println("The methodTwo in BaseClass");
    }
    public static void methodThree(){
        System.out.println("The methodThree in BaseClass");
    }
    public static void methodFour(){
        System.out.println("The methodFour in BaseClass");
    }
}
package cn.StaticDemo01;

public class DerivedClass extends BaseClass {
    /*
       静态方法只能被继承,不能被重写。子类中可以定义与父类相同的静态方法,此时只是将父类的方法隐藏,而不是覆盖它
     */
    //重写,覆盖
    public /*static*/ void methodOne(){
        System.out.println("The methodOne in DerivedClass");//将父类中的非静态成员方法变成静态的
    }
    //重写,覆盖
    public void methodTwo(){
        System.out.println("The methodTwo in DerivedClass");
       // super.methodTwo();
    }
    /*public void methodThree(){
        System.out.println("The methodThree in Derived Class");//将父类中的静态成员方法改成非静态的
    }*/
    //隐藏
    public static void methodThree(){ System.out.println("The methodThree in DerivedClass"); }
    //隐藏
    public static void methodFour(){ System.out.println("The methodFour in DerivedClass"); }
}

package cn.StaticDemo01;


public class StaticTest {
    public static void main(String[] args){
        BaseClass bc=new BaseClass();
        DerivedClass dc=new DerivedClass();

        bc.methodOne();                 //The methodOne in BaseClass
        bc.methodTwo();                 //The methodTwo in BaseClass
        BaseClass.methodThree();        //The methodThree in BaseClass
        BaseClass.methodFour();         //The methodFour in BaseClass

        dc.methodOne();                 //The methodOne in Derived Class
        dc.methodTwo();                 //The methodTwo in Derived Class
        dc.methodThree();               //The methodThree in Derived Class
        DerivedClass.methodFour();      //The methodFour in Derived Class

        BaseClass bc2 = new DerivedClass();
        发生隐藏时,不会出现动态绑定
        bc2.methodThree();               //The methodThree in BaseClass
        bc2.methodFour();               //The methodFour in BaseClass
        //重写了父类的方法,发生多态
        bc2.methodOne();                //The methodOne in DerivedClass
        bc2.methodTwo();                //The methodTwo in Derived Class
    }
}

结果:

静态方法只能继承,不能重写。子类中可以定义与父类相同的静态方法,此时只是将父类中的方法隐藏,而不是覆盖它。
隐藏:隐藏:父类和子类拥有相同名字的属性或者方法( 方法隐藏只有一种形式,就是父类和子类存在相同的静态方法)时,父类的同名的属性或者方法形式上不见了,实际是还是存在的。

关于隐藏和覆盖的讨论见:Java中的隐藏和覆盖

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值