0

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' ?

2
  • Yes, it is possible as to access the fields, just don't mark them private. float pt = myObj.myarrayobj[0];. Commented Oct 15, 2014 at 0:33
  • 2
    why do you need two different classes that have same content? Commented Oct 15, 2014 at 0:35

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.