0

When I created a subclass that have two constructors, I need to define a constructor SuperClass(int m) because my second constructor from the sub class is calling it super(). This is the part I understand. But the code will not compile unless I define another constructor in the SuperClass like SuperClass(){}, not SuperClass(int m, int n){} . Why?

public class SubClass extends SuperClass {

    int i,j,k;
    public SubClass(int m, int n){
        this.i = m;
        this.j=n;
    }
    public SubClass(int m){
        super(m);
    }
}
OPK
  • 4,120
  • 6
  • 36
  • 66

3 Answers3

3
public SubClass(int m, int n){
    this.i = m;
    this.j=n;
}

In the constructor above it is implied that a super class no-args constructor exists. It is the same as:

public SubClass(int m, int n){
    super(); // This was implied.
    this.i = m;
    this.j=n;
}

The other case is this:

public SubClass(int m){
    super(m);
}

Here you declare the you are using a super class constructor that takes one argument m.

So, basically your super class must declare two constructors to make the code work:

SuperClass() {
    // The default constructor
}

SuperClass(int m) {
    // one arg constructor...
}

However, if you specify the following super class constructor:

SuperClass(int m, int n){}

Then you could rewrite your sub class constructor like this:

public SubClass(int m, int n){
    super(m, n);
}

This article from Oracle explains the usage of constructors very well!

wassgren
  • 18,651
  • 6
  • 63
  • 77
1

One of your SubClass constructors does not call a constructor of the super class. If you do not specify a super constructor the JDK will assume the default constructor. If the super class has no default constructor then it cannot compile.

Stephen Souness
  • 272
  • 1
  • 3
0

In java when you explicitly define any constructor to a class. The default constructor is no more available and you need to define your the default constructor again.

And in subclass's constructor, by default the very first implicit statement will the super() in case you have not explicitly called any other super constructor

public class SubClass extends SuperClass {

    int i,j,k;
    public SubClass(int m, int n){
        super() //implicit
        this.i = m;
        this.j=n;
    }
    public SubClass(int m){
        super(m);
    }
}
Keen Sage
  • 1,899
  • 5
  • 26
  • 44