java怎么让一个类不能被继承,为什么我不能调用从继承类另一个包在Java中一个受保护的方法是什么?...

Say there's the following base class:

package bg.svetlin.ui.controls;

public abstract class Control {

protected int getHeight() {

//..

}

//...

}

Also, in the same package, there's a class that inherits:

package bg.svetlin.ui.controls;

public abstract class LayoutControl extends Control {

public abstract void addControl(Control control);

//...

}

Then, there's a third class in another package:

package bg.svetlin.ui.controls.screen;

public abstract class Screen extends LayoutControl {

//...

}

And, finally, there's the implementation class, again in a different package:

package bg.svetlin.ui.controls.screen.list;

public class List extends Screen {

private final Vector controls = new Vector();

public void addControl(Control control) {

height += control.getHeight();

controls.addElement(control);

}

}

Even though List inherits from Control, and the getHeight() is protected, there's the following error:

getHeight() has protected access in bg.svetlin.ui.controls.Control

I've checked that my imports are right. I'm using NetBeans.

Any idea what's wrong? I thought protected fields and methods are visible to the children even if the latter are in a different package.

Thanks!

解决方案

I thought protected fields and methods are

visible to the children even if the latter are in a different package.

That's correct. The class itself has an access to the inherited protected members. But, what you're trying to do it to call the getHeight method on some Control reference. You're allowed to call it only on this instance!

For a better understanding, let me quote Kathy Sierra's SCJP Preparation Guide:

But what does it mean for a subclass-outside-the-package to have

access to a superclass (parent) member? It means the subclass inherits

the member. It does not, however, mean the

subclass-outside-the-package can access the member using a reference

to an instance of the superclass. In other words, protected =

inheritance. The subclass can see the protected member

only through inheritance.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值