How do getters and setters work?

后端 未结 6 1982
北恋
北恋 2020-11-21 07:43

I\'m from the php world. Could you explain what getters and setters are and could give you some examples?

6条回答
  •  無奈伤痛
    2020-11-21 07:54

    Here is an example to explain the most simple way of using getter and setter in java. One can do this in a more straightforward way but getter and setter have something special that is when using private member of parent class in child class in inheritance. You can make it possible through using getter and setter.

    package stackoverflow;
    
        public class StackoverFlow 
    
        {
    
            private int x;
    
            public int getX()
            {
                return x;
            }
    
            public int setX(int x)
            {
              return  this.x = x;
            }
             public void showX()
             {
                 System.out.println("value of x  "+x);
             }
    
    
            public static void main(String[] args) {
    
                StackoverFlow sto = new StackoverFlow();
                sto.setX(10);
                sto.getX();
                sto.showX();
            }
    
        }
    

提交回复
热议问题