简体   繁体   中英

Is there a way I can call a parent class constructor that takes parameters from a child class that does not have a constructor of it's own?

As we all know, the parent class must be constructed before the child class; and if the parent's class constructor takes parameters, then the constructor of the parent class must be called explicitly. My question is, how do you call a parent class constructor that takes parameters explicitly from a child class, if the child class does not have a constructor itself?

public class A {
public String text;

public A(String text) {
    this.text = text;
}
}


public class B extends A {
// Now I must call the constructor of A explicitly (other wise I'll get a
// compilation error) but how can I do that without a constructor here?
}

The answer is: you can't!

In case the super class has a parameter free constructor, the compiler can add one like that for you in subclass, too.

But when the super class needs parameters, the compiler has no idea where these should come from.

So: consider adding a no args constructor to the super class, it could invoke the other constructor and pass some sort of default values. Alternatively, you can do the same in the derived class.

And just for the record: there are no Java classes without constructors. It is just that the compiler might create one for you behind the covers. From that point of view, your question does not make much sense.

You are getting compilation error because there is no default constructor in class A . You can create a no-arg constructor in B and pass some default text to A 's contructor, or create a no-arg constructor in A .

public B() {
    super("some default text"); //will call public A(String text)
}

If you're not willing to call the parent constructor directly, you'll just need to add a constructor with the same parameters in the child class that just calls the parent constructor.

public class A { 
    public String text; 

    public A(String text) 
    { 
        this.text = text; 
    } 
} 

public class B extends A 
{
    public B(String text)
    {
        super(text);
    }
}

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