[英]In Java, can you call a parent class's superclass constructor through the constructor of the child class of the parent class?
[英]Java: How Can be child class constructor class neutralize parent constructor?
子类构造函数类如何能够中和父构造函数?
我的意思是在Child构造函数中我们必须使用super() - 是否存在创建父对象的方法?
超级示例:
class abstract Parent{
protected String name;
public Parent(String name){
this.name=name;
}
}
class Child extends Parent{
public Child(String name,int count){
super(name);
}
}
“父母”和“孩子”在这里不合适。 一个孩子不是一种父母(我当然希望我的孩子至少再过十年,但这是另一回事)。
考虑使用不同名称的相同代码:
class abstract Animal{
protected String name;
public Animal(String name){
this.name=name;
}
}
class Elephant extends Animal{
public Elephant(String name,int count){
super(name);
}
}
现在,你怎么能有一只不是动物的大象呢?
子类可以通过super.ParentClassVariable = thingToBeChanged更改父构造函数中指向的对象;
class Parent
{
BufferedReader inKeyboard;
public Parent()
{
inKeyboard = new BufferedReader (new InputStreamReader(System.in));
}
}
class Child extends Parent
{
public Child()
{
super.inKeyboard = new BufferedReader(new FileReader(filename));
}//changes the pointer in the parent object to point to a different reader
}
现在当你创建一个子对象时,而不是让父使用...(System.in)中的方法作为输入,Parent中的方法将使用...(文件名)
扩展父对象,初始化子对象时初始化该对象。 作为初始化的要求,父母需要一个名字。 这只能在子对象的初始化中给出。
那么回答你的问题,不
你为什么要继承一些东西而不是构建它? 如果您的代码需要,那可能是因为糟糕的设计。 Java确实需要您调用父的构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.