我创建类层次结构:为什么要从外部类访问受保护的成员?
abstract class Shape{
protected abstract float getArea();
protected abstract float getVolume();
}
abstract class TwoDimentionalShape extends Shape{
public abstract float getArea();
protected float getVolume(){
return 0;
}
}
class Square extends TwoDimentionalShape {
float width, height;
Square(float w, float h){
width = w;
height = h;
}
public float getArea(){
return width*height;
}
}
public class ShapeTest {
public static void main(String args[]){
Shape s = new Square(3, 4);
System.out.println(s.getVolume());
}
}
我希望做的是隐藏功能getVolume()
为TwoDimentionalShape
类,因为它会被用于ThreeDimentionalShape
类。
问题是我已经声明该函数是受保护的,但是当我从main()
调用它时,程序正在工作。这是为什么发生?
'对不起,但保护被用来访问包外...你正在谈论的默认访问修饰符,它具有包级访问...受保护的成员可以继承和访问其子类OUTSIDE包装。 –
是的你是对的。我会更新并使答案更清晰 – RNJ
好,所以我明白了这个问题。为了实现我希望实现的目标,我在2DShape的getvolume中添加了异常。谢谢 –