Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
  }    
}
like image 799
Ben Avatar asked Dec 13 '25 07:12

Ben


2 Answers

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

like image 198
Jon Hanna Avatar answered Dec 14 '25 20:12

Jon Hanna


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

like image 20
TheLQ Avatar answered Dec 14 '25 19:12

TheLQ