Reputation: 13
I want to initialize instance variables with constructors but I get a compile error.
class Test{
public static void main(String[] args){
A a = new A(5,6);
System.out.println(a.i);
}
}
class A{
int i, k;
A(int a, int b){
this.i=a;
this.k=b;
}
}
class B extends A{
int k;
B(int a, int b, int c){
this.k = a;
}
}
The error is:
Test.java:26: error: constructor A in class A cannot be applied to given types;
B(int a, int b, int c){
^
required: int,int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Upvotes: 0
Views: 156
Reputation: 2020
Well, your problem is that you cannot construct an object B without constructing first an object A. If you had a default constructor in A, you wouldnt need to call super in B ( it will be automatically called though ).
Upvotes: 0
Reputation: 37594
You are missing the super
call in B
. You can fix it by using
class B extends A{
int k;
B(int a, int b, int c){
super(a,b);
this.k = a;
}
}
Also you probably meant to use this.k = c
.
Upvotes: 3