以下代码输出为:(numberOfInstances)
class Parent
{
public int numberOfInstances;
protected Parent(int numberOfInstance)
{
this.numberOfInstances=numberOfInstance;
}
}public class Example extends Parent
{
private Example(int numberOfInstances)
{
super(numberOfInstances);
}
public static void main(String...strings)
{
Example ext=new Example(420);
System.out.println(ext.numberOfInstances);
}
}
class Parent
{
public int numberOfInstances;
protected Parent(int numberOfInstance)
{
this.numberOfInstances=numberOfInstance;
}
}public class Example extends Parent
{
private Example(int numberOfInstances)
{
super(numberOfInstances);
}
public static void main(String...strings)
{
Example ext=new Example(420);
System.out.println(ext.numberOfInstances);
}
}
Example 的构造器是私有的,在类的外部无法调用(外面调用报错),但是main方法在类的内部可以访问到。Example继承了Parent的numberOfInstances属性,构造器引用父类构造器进行赋值。