今天在学习关于继承的时候想到一个问题,子类不可以继承父类的私有成员,那么可以通过非私有成员访问其私有成员吗?为了验证这一点,我写了如下代码:
package newpack;class FatherFour{
private static int i;
FatherFour(){
System.out.println("Hello");
} //各位大虾注意此处。
FatherFour(int getI){
i=getI;
}
static int getI(){
return i;
}
}
public class PrivateExtends extends FatherFour{
public static void main(String[]args){
FatherFour test=new FatherFour(1);
System.out.println(getI());
}}
结果输出一,说明可以通过继承得来的非私有成员来访问父类的私有成员。
但是有个很奇怪的问题,那就是我刚开始写的代码没有上边注明的那一个构造器,结果出错。
信息如下:Implicit super constructor FatherFour() is undefined for default constructor. Must define an explicit constructor。
后来我加上了这个构造方法就通过了,真奇怪。请问这是怎么回事?谢谢!
package newpack;class FatherFour{
private static int i;
FatherFour(){
System.out.println("Hello");
} //各位大虾注意此处。
FatherFour(int getI){
i=getI;
}
static int getI(){
return i;
}
}
public class PrivateExtends extends FatherFour{
public static void main(String[]args){
FatherFour test=new FatherFour(1);
System.out.println(getI());
}}
结果输出一,说明可以通过继承得来的非私有成员来访问父类的私有成员。
但是有个很奇怪的问题,那就是我刚开始写的代码没有上边注明的那一个构造器,结果出错。
信息如下:Implicit super constructor FatherFour() is undefined for default constructor. Must define an explicit constructor。
后来我加上了这个构造方法就通过了,真奇怪。请问这是怎么回事?谢谢!
如果没有写构造器,那默认是调用父类的无参构造器。public class PrivateExtends extends FatherFour{
public static void main(String[]args){
FatherFour test=new FatherFour(1);
System.out.println(getI());
}
PrivateExtends() {
super(1);
}}这样,就可以把父类的无参构造器去掉了。
------------------------------
打错了。
应该是那就无法调用父类的构造器。believefym(暮色,miss,迷失,miss)
解释的好。