javaooplanguage-concepts

How should I change a class value from another


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.


Solution

  • 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());
        }
    }