java 继承 变量覆盖,Java继承覆盖实例变量

I am learning java. I have a doubt in inheritance. When a child class extends parent class and parent class has a method which refers to a instance variable declared in parent. But the child class dint override this method and has declared instance variable with same name as the parent. In this case instance variable from child will be referred or parent will be referred. Below is the code snippet

class parent {

int a;

parent() {

System.out.println("in parent");

a = 10;

}

void method() {

System.out.println(a);

}

}

class child extends parent {

int a;

child() {

System.out.println("in child");

a = 11;

}

}

public class Test {

public static void main(String args[]) throws IOException {

parent p1 = new child();

p1.method();

}

}

The output I get is

in parent

in child

10

Can someone please make me understand why its referring parent class's instance variable a and not child class's a.

Another doubt is, I understood hiding the method, when there is a static method in parent and child class also has declared a static method with same signature. Here hiding means ? what method is getting hidden ? If its the parent method can you please explain me ?

Thanks in advance.

解决方案

Java instance variables cannot be overridden in a subclass. Java inheritance doesn't work that way.

In your example, there is no method hiding (or overriding or overloading) going on.

There is hiding of instance variables though. In class child, the declaration of a hides the declaration of a in parent, and all references to a in the child class refer to the child.a not the parent.a.

To illustrate this more plainly, try running this:

public static void main(String args[]) throws IOException {

child c1 = new child();

parent p1 = c1;

System.out.println("p1.a is " + p1.a);

System.out.println("c1.a is " + c1.a);

System.out.println("p1 == c1 is " + (p1 == c1));

}

It should output:

p1.a is 10

c1.a is 11

p1 == c1 is true

This demonstrates that there is one object with two distinct fields called a ... and you can get hold of both of their values, if the access permits it.

Finally, you should learn to follow the standard Java identifier conventions. A class name should ALWAYS start with a capital letter.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值