java抽象类的字段,Java抽象类字段重写

I have an abstract class that should implement a public field, this field is an interface or another abstract classe.

something like this:

public abstract class GenericContainer {

public GenericChild child;

}

public abstract class GenericChild {

public int prop1=1;

}

public abstract class SpecialChild extend GenericChild {

public int prop1=2;

}

Now i have another specialized class Container:

public abstract class SpecialContainer extends GenericContainer {

public SpecialChild child=new SpecialChild(); //PAY ATTENTION HERE!

}

Java allow me to compile this, and i IMAGINE that the field child in SpecialContainer is automatically overloading the field child of the GenericContainer...

The questions are:

Am i right on this? The automatic 'overloading' of child will happen?

And, more important question, if i have another class like this:

public class ExternalClass {

public GenericContainer container=new SpecialContainer();

public int test() {

return container.child.prop1

}

}

test() will return 1 or 2? i mean the GenericContainer container field what prop1 will call, the generic or the special?

And what if the special prop1 was declared as String (yes java allow me to compile also in this case)?

Thanks!

解决方案

It isn't overriding anything, you're just hiding the original field at the current class scope. If you use a variable with the subtype you will still be able to access the original property. Example:

abstract class GenericContainer {

public GenericChild child;

}

abstract class GenericChild {

public int prop1=1 ;

}

class SpecialChild extends GenericChild {

public int prop1=2;

}

class SpecialContainer extends GenericContainer {

public SpecialChild child;

}

public class Main {

public static void main( String ... args ) {

GenericContainer container = new SpecialContainer();

container.child = new SpecialChild();

System.out.println( container.child.prop1 );

SpecialChild child = (SpecialChild) container.child;

System.out.println( child.prop1 );

}

}

This prints 1 and then 2.

From SpecialChild you would also be able to go up one level using super:

class SpecialChild extends GenericChild {

public int prop1=2;

public int getOriginalProp1() {

return super.prop1;

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值