I've 3 classes
Class A{
int a;
int b;
public A(){}
public A(int a, int b){
this.a = a;
this.b = b;
}
}
Class B extends Class A{
int c;
int d;
public B(){}
public B(int c, int d){
this.c = c;
this.d = d;
}
}
Class C extends Class B{
int f;
public C(int f){
this.f = f;
}
}
Now, I'm receiving an object of B(with a, b, c & d values set) from somewhere and f's value as well and I want to create a new instance of C with all the values set. Hence, I created a new constructor in Class C
Class C extends Class B{
int f;
C(int f){
this.f = f;
}
C(int f, B bInstance){
super(bInstance);
this(f); // because I wanted to only one base constructor
}
}
Added constructor in B
Class B extends Class A{
int c;
int d;
B(int c, int d){
this.c = c;
this.d = d;
}
B(B bInstance){
super(B.getA(), B.getB());
this(B.getC(), B.getC());
}
}
Now, this() and super() both needs to be the first statement. Hence, I can't have it this way. I was doing it this way in spirit of keeping only one base constructor and every other constructor calling this one. Here is a link supporting this Best way to handle multiple constructors in Java.
Otherwise, the simple solution would be to have a new constructor in class C and B
Class C extends Class B{
int f;
C(int f){
this.f = f;
}
C(int f, B bInstance){
super(bInstance);
this.f = f;
}
}
Class B extends Class A{
int c;
int d;
B(int c, int d){
this.c = c;
this.d = d;
}
B(B bInstance){
super(B.getA(), B.getB());
this.c = c;
this.d = d;
}
}
But, I'm trying to learn the best coding standards and wanted to know how to implement it with the best coding practices.