0

I am learning to program in Java, and I want to know if it is a good concept of OO programming to change a value to a composed class from another composed class. Like this:

public class X{
    public void x(Y y){
        y.setY(0);
    }
}

A simple example of the structure 1

Or should I appeal to the Main class? Like this:

public class X{
    public void x(Main m){
        m.modifyY(0);
    }
}

public class Main{
    private Y y;
    private X x;

    public void modifyY(Main m){
        y.modifyY(0);
    }
}

A simple example of the structure 2

PS: I am learning UML too, so I'm sorry if I'm making it wrong.

mhawke
  • 84,695
  • 9
  • 117
  • 138
  • You can do it both ways. but I don't see any reason to change a variable value you need to pass it to another class and then modify it. How about directly using getter and setter ? – Lokesh Pandey Apr 25 '18 at 10:08

2 Answers2

1

You can change like this,

public class X{
    public X(Y y){
        y.setY(0);
    }
}

public class Y{
   public int val=0;
   public void setY(int p_val){
       val=p_val;
   }
}

public class Main{
    public void modifyY(){
         new X(new y());
    }
}
Balayesu Chilakalapudi
  • 1,386
  • 3
  • 19
  • 43
1

generally you want to keep you classes as decopeled as possible, so you want to change a class value you ask the class itself to change it. so if the sole purpose of your class is changing a value of another one, then it is unnecessary, you should just call y.setY(0); from the method that uses y

user1
  • 254
  • 1
  • 15