I need to instantiate a class during runtime based what a user has selected in a list, but these classes each have their own new specific functions and variables, they use the same named functions, but set different variables, and different numbers of variables.
I made an example, since my actual code has classes i made which you'd need to import
class tester {
public void tester(){};
public void main(){
int x=1;
if (x==0){
class1 newobj = new class1();
}
else if (x==1){
class2 newobj = new class2();
}
newobj.testfunc();
}
private class class1{
public void testfunc(){
System.out.println("class1");
}
}
private class class2{
public void testfunc(){
System.out.println("class2");
}
}
this gives me a variable newobj not found error
so I made a general superclass just to declare a variable at the start, and then cast it and use their functions after the choice check
class tester {
public void tester(){};
public void main(){
int x=1;
Object newobj;
if (x==0){
newobj = new class1();
newobj = (class1)newobj;
}
else if (x==1){
newobj = new class2();
newobj = (class2)newobj();
}
newobj.testfunc();
}
private class class1 extends Object{
public void testfun(){
System.out.println("class1");
}
}
private class class2 extends Object{
public void testfunc(){
System.out.println("class2");
}
}
}
which gave me a method not found error...
so I made a superclass with the method
class tester {
public void tester(){};
public void main(String[] args){
int x=1;
superclass newobj;
if (x==0){
newobj = new class1();
newobj = (class1)newobj;
}
else {
newobj = new class2();
newobj = (class2)newobj;
}
newobj.testfunc();
}
private class superclass{
public void testfunc(){
System.out.println("superclass");
}
}
private class class1 extends superclass{
int specialvariable;
public void testfunc(){
System.out.println("class1");
specialvariable = 100
}
}
private class class2 extends superclass{
int specialvariable2;
public void testfunc(){
System.out.println("class2");
specialvariable2 = 100
}
}
}
This just runs the method of the superclass
I don't understand why this last method doesn't work...
Even though I use the subclass' constructor to initialize it and cast it as well, how come I don't get an object of that specific subclass?
Some other info:
The user will have an item in a JList selected, then clicking on a panel will create a specific label subclass I defined in the package, the classes aren't inner classes like here, but I get the same problems. And after being created they all call the same method (by same I mean same name, different actions/variables) outside the if statements, so no matter what they picked I can just write that newobj.method() once, like in that example