mq007 mq007 - 1 year ago 65
Java Question

Different arguments in function

For example, I got a class X which got 2 fields named ex. aField and bField. In main class I got table of object class X and the function which should be called to times, but in first time it must change fields named aField and in second call must change fields named bField.

class X{
int aField;
int bField;
class Main{
public X[] listX;
public int amount;
public static void requestedFunction(){
for(int i=0; i<amount; i++){
aField = 5;
// bField = 5;
// or this one when called second time in code ;

public static void main(String[] args) {
amount = 10;
listX= new X[amount];

requestedFunction(); // thsi usage change fields named aFields
requestedFunction(); // this usage change fields named bFields

Is there any solution to make it in this way? Or I need to make 2 different functions?

Answer Source

Technically you can achieve this with

enum ExecutionType {

public static void requestedFunction(ExecutionType eType){
    for(int i=0; i<amount; i++){
        if (eType==ExecutionType.ATYPE)
            aField = 5;
        else if (eType ==ExecutionType.BTYPE)
            bField = 5; 


However, the correct way to achieve this is using two separate functions. This design is not so nice and has potential to cause serious headache for more complex scenarios.

You version that uses no parameters is also possible but defies more and more object oriented principals. It would be very difficult to understand the behavior of a function that does different things each time it's called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download