简体   繁体   中英

Java: How Can be child class constructor class neutralize parent constructor?

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?

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);
  }    
}

"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?

A child class can change what the objects in a parent constructor point to via 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)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM