为了账号安全,请及时绑定邮箱和手机立即绑定

关于super.age为啥子给出的是子类Dog.age中的值????

关于super.age为啥子给出的是子类Dog.age中的值????

olo 2017-03-06 19:05:33
给父类Animal中的int age属性数值1;如果没有在Dog子类里定义int dog ;public void method( ){System.out.println(super.age);}在mian执行如下  dog.age=9;  dog.method( );就会直接给出值9,(animal.age实际上等于=1,而且如果在Dog类里加上 int age,就会给出值1)super不是调用父类的属性值吗?这是为什么?哪里出问题了?求 大佬解释
查看完整描述

1 回答

?
qq_随心_57

TA贡献8条经验 获得超3个赞

因为你有这个dog.age=9;这句代码相当于是给父类Animal中的age变量重新赋值为9了,所以输出才为9.

如果在Dog类里加上 int age,你这就相当于是没有给父类Animal中的age变量赋新值,所以为1.


/**

*下述代码输出结果为1(父类Animal中age初始化值为1)

*/

public class Dog extends Animal {
    public void method(){
        System.out.println(super.age);
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int age=9;
        Dog dog=new Dog();
        dog.method();
    }
}

/**

*下述代码输出结果为9(父类Animal中age初始化值为1)

*/

public class Dog extends Animal {
    public void method(){
        System.out.println(super.age);
    }
    public static void main(String[] args) {
//        int age=9;
        Dog dog=new Dog();
        dog.age=9;     //给父类Animal中age赋新值
        dog.method();
    }
}


查看完整回答
反对 回复 2017-03-06
  • 1 回答
  • 0 关注
  • 1652 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信