Java 继承对 方法 与 变量 处理的方式

直接上代码:

public class Test
{
    public static class A 
    {
        private int i = 0;

        protected void doAdd()
        {
            i ++;
        }

        public void printOut ()
        {   
            System.out.println (this.i);
            this.doAdd ();
            System.out.println (this.i);
        }
    }

    public static class B extends A
    {
        private int i = 1;
        @Override
        protected void doAdd ()
        {
            i = i + 2;
            System.out.println("__" + this.i);
        }
    }

    public static void main (String [] args)
    {
        A a = new A ();
        a.printOut ();
        B b = new B ();
        b.printOut ();
        a = b;
        a.printOut ();
    }
}
/*
输出结果:
0
1
0
__3
0
0
__5
0
*/

可能会这么理解:

当 b 调用 pirntOut() 的时候,会调用父类 a 里面的 printOut() 方法
执行 this.doAdd() 的时候会判断 B 里面是否有该方法
这里的话 是重写了 doAdd() 方法的,所以会执行 b 里面的 doAdd() 方法

但是当调用到 this.i 的时候 会先判断 B 的 i 是否能调用,然而 i 是 private 修饰的 ,所以只能往上,看父类里面有没有 i ,然后调用父类的 i

这样看起来结果似乎是正确的,但是把代码中的 private 都去掉之后,变成这个样子

public class Test
{
    public static class A 
    {
        int i = 0;

        protected void doAdd()
        {
            i ++;
        }

        public void printOut ()
        {   
            System.out.println (this.i);
            this.doAdd ();
            System.out.println (this.i);
        }
    }

    public static class B extends A
    {
        int i = 1;
        @Override
        protected void doAdd ()
        {
            i = i + 2;
            System.out.println("__" + this.i);
        }
    }

    public static void main (String [] args)
    {
        A a = new A ();
        a.printOut ();
        B b = new B ();
        b.printOut ();
        a = b;
        a.printOut ();
    }
}
/*
输出结果:
0
1
0
__3
0
0
__5
0
*/

不得不承认,不是private的关系。
真正原因如下:
对于继承的 方法 和 变量 调用的时候,处理方式不一样
当调用方法的时候, 会判断当前类是否重写该方法,如果有就调用自己的,没有的话就线上转型调用父类的
比如 B 调用 doAdd() 会看B里面是否重写该方法 这里重写了 就调用B自己的doAdd()

但是在调用同名变量的时候,this 在谁类里面,就调用当前类的变量
this.i在A类中 调用 this.i的时候 不会去B里面找是否有 i可以调用,直接调A里面的i

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值