Ben
Ben

Reputation: 25807

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

Upvotes: 3

Views: 11532

Answers (4)

CaptainNicCard
CaptainNicCard

Reputation: 11

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)

Upvotes: 1

Jon Hanna
Jon Hanna

Reputation: 113282

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

Upvotes: 4

Ruan Mendes
Ruan Mendes

Reputation: 92274

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.

Upvotes: 1

TheLQ
TheLQ

Reputation: 15008

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

Upvotes: 1

Related Questions