Home > Mobile >  Using object property as function parameter
Using object property as function parameter

Time:10-09

Imagine you have a Point myPoint object with a .x and .y property. How would you write a function void multiply() that used myPoint.x or myPoint.y as an input, and multiplied the value of .x or .y in the object. Keep in mind the problem is being able to input myPoint.x, .y, .z or any property of the object and saving the result in the myPoint.whatever variable. This would be the class:

Point{
 int x,y;

 //Im ignoring the constructor

 void multiply(int Point.x number, int factor) //Being int Point.x or .y my problem
  number*=factor; //saving the value of number in Point.x
}

CodePudding user response:

You would just refer to x and y in your function:

void multiply(int factor) { 
    this.x *= factor; 
    this.y *= factor; 
}

If you want methods that specifically factor certain fields, I'd recommend method calls that make this clear:

void multiplyX(int factor) { 
    this.x *= factor; 
}

If you want to factor only one particular variable that you want to specify when you call the function, that's probably not something you actually want to do. You could do it with a lambda, and if you want me to edit this question to explain that, just leave a comment; but that seems like a lot more trouble than it's worth from a API and maintenance perspective.

CodePudding user response:

Java doesn't have pointers/references to primitive (non-object) values. You can emulate them either by defining an interface for accessing a value:

public interface IntAccess {
  void set(int);
  int get();
}

public class Point {
  int x,y;

  IntAccess accessX() {
    return new IntAccess() {
      public void set(int v) {x=v;}
      public int get() {return x;}
    }
  }
  IntAccess accessY() {
    return new IntAccess() {
      public void set(int v) {y=v;}
      public int get() {return y;}
    }
  }

  public static void multiply(IntAccess i,int f) {i.set(i.get()*f);}
}

class Client {
  static void test() {
    Point p=new Point();
    Point.multiply(p.accessX(),3);
    Point.multiply(p.accessY(),4);
  }
}

Alternatively, you can make the fields be objects:

public class Multiplyable {
  int v;
  public void multiply(int f) {v*=f;}
}

public class Point {
  public Multiplyable x,y;
}

class Client {
  static void test() {
    Point p=new Point();
    p.x.multiply(3);
  }
}
  • Related