views:

52

answers:

3

Hi,

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

I mean in Child constructor we have to use super()- does exist way not to create parent object ?

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

}
+1  A: 

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

TheLQ
+2  A: 

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.

Juan Mendes
+2  A: 

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

Jon Hanna