Reputation: 1
I'm learning Java at school and I have encountered a problem with inheritance and constructors. I have 3 classes, Class A, Class B and Class C. Class A is the superclass, Class B extends class A and Class C extends Class B. Class B has a constructor whose formal(parameter) is a String. All good till here. So now, I extend Class B to Class C. In Class C I need to create a constructor that has an instance of Class B as its parameter. I then need to extract some information from Class B and store that in Class C.
Here is the code we have.
public class B extends A {
int b;
public B(int b) {
this.b=b;
}
}
public class C extends B {
int c;
public C(B b) {
this.c = b.b;
}
}
In my main()
I have the following line of code to create an instance of C
C c_c = new C(new B(12));
When this is compiled, I get an error. error: constructor B in class B cannot be applied to given types;
reason: actual and formal argument lists differ in length
Would you guys be able to help me understand what I've done wrong?
Upvotes: 0
Views: 788
Reputation: 136002
You dont need to reload information from B to C. Simply make B's fields visible to C eg make them protected
Upvotes: 0
Reputation: 18569
You must explicitly call B's constructor from C's constructor since no default constructor defined in class B
public C(B b) {
super(0);
this.c = b.b;
}
Upvotes: 2