[英]Why calling private method with subclass object inside superclass constructor is possible …?
class ParentClass
{
double height;
public ParentClass()
{
height=10;
System.out.println("this : "+this.getClass().getName());
showHeight();
}
private void showHeight()
{
System.out.println("Height is : "+height);
}
}
class ChildClass extends ParentClass
{
double weight;
public ChildClass(double weight)
{
this.weight=weight;
}
}
public class CallingPrivateMethod
{
public static void main(String arg[])
{
ChildClass childObj=new ChildClass(32.65);
}
}
This will print the following : 这将打印以下内容:
this : ChildClass 这:ChildClass
Height is : 10.0 高度是:10.0
You're not calling the private method from the subclass; 您不是在子类中调用private方法; it's being invoked by the superclass (ParentClass) in its constructor, and that constructor is in turn invoked from the subclass.
它由其构造函数中的超类(ParentClass)调用,而该构造函数又从子类中调用。 It's no different than any other time a base class invokes a private method.
这与基类调用私有方法没有什么不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.