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

11,114

Solution 1

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

Solution 2

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

Solution 3

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.

Solution 4

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)

Share:
11,114
Ben
Author by

Ben

Updated on June 04, 2022

Comments

  • Ben
    Ben almost 2 years

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