java 子类 类名_Java继承混淆,超类和子类成员变量具有相同的名称(Java inheritance confusion, superclass and subclass member vari...

On running this code

class c1 { int ci = 1; }

class c2 extends c1 { int ci = 2; }

class inheritanceTest {

public static void main(String args[]) {

c1 c1reftoc2 = new c2();

System.out.println(c1reftoc2.ci);

}

}

Output is 1. So i guess that a subclass object with superclass reference variable, uses superclass variable in case of variables of same name in both classes.

But then, running this program from a SCJP question,

class Foo {

public int a = 3;

public void addFive() {

a += 5;

System.out.print("f ");

}

}

class Bar extends Foo {

public int a = 8;

public void addFive() {

System.out.println(this.a);

this.a += 5;

System.out.print("b " );

System.out.println(this.a);

}

}

class SCJPQC3 {

public static void main(String[] args) {

Foo f = new Bar();

f.addFive();

System.out.println(f.a);

}

}

output is

8

b 13

3

The addFive() method called in main() would be that of class Bar because of overriding.

this.a in addFive() prints 8. Whereas f.a in main() gives 3. Instances being referred by this. and f. are same, yet they give different results. Using this.a gives 8 as output which contradicts my previous understanding.

So my question is, does this. refer to a class or an instance? I know that this. would refer to the object through which a method is called, but this particular program confused me.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值