父类、子类成员同名时的歧义

父类、子类中变量名相同时

public class Main {
    public static void main(String args[])
    {
        A a=new B();
        System.out.println(a.n);//输出1,即A的n值。
    }
}
class A
{
    int n=1;//若注释掉这句,则编译失败.n cannot be resolved or is not a field
}
class B extends A
{
    int n=2;//A a=new B(); 跟这个n没关系
}

父类、子类中成员函数名相同时

public class M1 {

    public static void main(String[] args) {
        C c=new D();
        c.run();//输出D
    }

}

class C
{
    void run(){System.out.println("C");}//若没有这句,则编译失败。The method run() is undefined for the type C
}
class D extends C
{
    void run(){System.out.println("D");}//这句是C类中run()方法的重写。若没这句,输出C。若有这句,输出D。
}

父类、子类中静态方法名相同时

package 子父类歧义;

public class M2 {

    public static void main(String[] args) {
        E e=new F();
        e.run();//输出E。
        //有警告:The static method run() from the type E should be accessed in a static way
        /* 成员函数是动态地绑定到类上。
         * 静态函数是静态地绑定到类上。哪个类调用的,就返回哪个类里的方法。如:E.run();
         * 静态函数在静态方法区,有别于普通成员函数的重写。
         */
    }
}
class E
{
    static void run(){System.out.println("E");}
}
class F extends E
{
    static void run(){System.out.println("F");}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值