user4258664
user4258664

Reputation:

Define constructor in subclass that is different from the superclass constructor?

I'm having this weird question on my homework assignment. Below there is a class declaration.

public class A {
private String str;
private int num;
   public A ( String str, int num ) {
     this.str = str;
     this.num = num;
}

Now I need an implementation of a subclass that is inherited from the A class, but has a different constructor like so:

public class B extends A {
private String str1;
   public B ( String str, String str1 ) {...}

// this is where the editor shows an error because class B constructor arguments are 
// different from the arguments in the class A constructor

but I need this constructor to be different. How can I do this?

Upvotes: 0

Views: 622

Answers (3)

Wael Sakhri
Wael Sakhri

Reputation: 397

You must use the super() statement :

public B ( String str, String str1 ) {

    //0 is the second int argument of the class A constructor
    super(str, 0);

    //do something with the str1
}

Because your class A doesn't have anymore the default no args constructor that is created by the compiler if you don"t have any constructor defined in your class

Upvotes: 1

Jörn Buitink
Jörn Buitink

Reputation: 2916

You need to call the super constructor explicitly:

public class B extends A {
private String str1;
    public B ( String str, String str1 ) {
        super(str,0);
        //do what you want...
    }

Upvotes: 2

Placinta Alexandru
Placinta Alexandru

Reputation: 503

First of all your Base class has custom constructor but doesnot have default, this will lead to compile error. Derived class will call implicit default constructor of base class in first line of derived class constructor or you can call necessary base constructor (super(..)) depends on your needs, after that is calling constructor body that goes next. So it's not problem to have different constructors.

Upvotes: 2

Related Questions