Java:子类构造函数类如何中和父构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3507780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: How Can be child class constructor class neutralize parent constructor?
提问by Yosef
How Can be child class constructor class neutralize a parent constructor?
子类构造函数类如何中和父构造函数?
I mean in Child constructor we have to use super()- does a way to create a parent object exist?
我的意思是在 Child 构造函数中我们必须使用 super()- 是否存在创建父对象的方法?
Example with 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);
}
}
采纳答案by TheLQ
You extend the parent object, which is initialized when you initialize the child. Well as a requirement to be initialized, the parent requires a name. This can only be given in the initialization of the child object.
您扩展父对象,该对象在您初始化子对象时被初始化。作为初始化的要求,父级需要一个名称。这只能在子对象的初始化中给出。
So to answer you question, no
所以要回答你的问题,不
回答by Jon Hanna
"Parent" and "child" are not appropriate words here. A child is not a type of parent (I certainly hope my children aren't for at least another decade, but that's another matter).
“父母”和“孩子”在这里不是合适的词。孩子不是一种父母(我当然希望我的孩子至少再过十年不是这样,但那是另一回事)。
Consider the same code with different names:
考虑具有不同名称的相同代码:
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);
}
}
Now, how can you have an elephant that isn't an animal?
现在,你怎么能拥有一头不是动物的大象呢?
回答by Juan Mendes
Why would you be subclassing something but not constructing it? If your code requires that, that's probably because of bad design. Java does require that you call the parent's constructor.
为什么你要对某些东西进行子类化而不是构造它?如果您的代码需要这样做,那可能是因为设计不当。Java 确实要求您调用父级的构造函数。
回答by CaptainNicCard
A child class can change what the objects in a parent constructor point to via super.ParentClassVariable = thingToBeChanged;
子类可以通过 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
}
Now the when you make a child object, instead of having methods in Parent use ...(System.in) as input, the methods in Parent will use ...(filename)
现在,当您创建子对象时,Parent 中的方法不再使用 ...(System.in) 作为输入,而是 Parent 中的方法将使用 ...(filename)

