I have multiple classes with different names, but they all have the same variable names. I would like to pass them to a single method and access the variables directly. The example below only shows two but I have many more.
Class1{
float x,y;
MyArrayObj myarrayobj;//this is new'ed.
}
Class2{
float x,y;
MyArrayObj myarrayobj;//this is new'ed.
}
static myGenericMethod(GenericClassObj myObj){
float x = myObj.x;
float pt = myObj.myarrayobj.array[0];
}
Is this possible, or do I have to use "getters/setters' ?
If all of these classes share common fields, extract those fields to a superclass and make your existing classes extend that. Then your generic method takes an object of the superclass type and accesses the fields directly.
abstract MySuperClass{
float x,y;
MyArrayObj myarrayobj;//this is new'ed.
}
Class1 extends MySuperClass{
// Class1 specific fields and methods
}
Class2 extends MySuperClass{
// Class2 specific fields and methods
}
static myGenericMethod(MySuperClass myObj){
float x = myObj.x;
float pt = myObj.myarrayobj.array[0];
}
Make the superclass abstract (as above) if you don't want it to be instantiated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.