Reputation: 171
I am learning java. The book I'm reading has a question which asks what is wrong with the following code? I have typed the code in NetBeans and I can see the error but why is this error caused and how is it resolved?
The error is highlighted over the code public A(int t)
and it says
Constructor B in class B cannot be applied to given types, require int, found no arguments, reason actual and formal arguments lists differ in length.
Here is the code:
public class Test {
public static void main(String[] args) {
B b = new B(5);
}
}
class A extends B {
public A(int t) {
System.out.println("A's constructor is invoked");
}
}
class B {
public B(int k) {
System.out.println("B's constructor is invoked");
}
}
Upvotes: 2
Views: 262
Reputation: 46408
when your super class
has an args constructor
and doesn't have a no-args constructor you have to explicitly invoke it using a super(args)
call from sub-class constructor
class A extends B {
public A(int t) {
super(t);
System.out.println("A's constructor is invoked");
}
}
Upvotes: 4
Reputation: 159774
You need to call the constructor of the super class as the first statement in A(int)
:
public A(int t) {
super(t);
System.out.println("A's constructor is invoked");
}
Upvotes: 1
Reputation: 83527
The class B has only one constructor which takes an int
argument. On the other hand, the constructor you have in class A (implicitly) tries to call a constructor in A's super class (namely B) that takes no arguments. This is the cause of the error. There are at least two ways to fix the problem:
Create a no-arg constructor in class B.
Explicitly call the constructor in class B which takes an int as a parameter. You can do this using the super
keyword.
Upvotes: 1
Reputation: 15278
Class B has defined constructor, so it does not have public implicit default constructor (with no arguments). All subclass constructors have to explicitly call superclass constructors, via super(t)
, if zero argument superclass constructor is not available.
Upvotes: 1