I have an abstract superclass that has concrete methods used by my subclasses. In at least one of my methods, I would like to return a new object of the same type.
For a better example I have a class A with a field (int num). I have class B which extends A and I create a class B object named classB. classB.someMethod should square num and return a new class B object with this squared value. I don't want to alter the original instance.
I've read about reflection a bit because that's what came up a lot during my searches. newInstance() was suggested frequently. I've also read that reflection can be bad. Is there a better way to go about with what I am trying to do? It's for a personal class I'm creating for openGL programming and could do it many ways but always try to practice keeping things as simple as possible. I could elaborate on my class if needed.
public class A(){
private int num;
public A(int num){
this.num = num;
}
public A square(A a){
temp = a.num * a.num;
return new class same type as the sublcass(temp);
}
}
public class B extends A(){
public B(int num){
super(num);
}
}
public static void main(String...args){
B first = new B(4);
B second = B.square();
}
return new B(whatever);?