How do getters and setters work?

后端 未结 6 1967
北恋
北恋 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

    class Clock {  
            String time;  
    
            void setTime (String t) {  
               time = t;  
            }  
    
            String getTime() {  
               return time;  
            }  
    }  
    
    
    class ClockTestDrive {  
       public static void main (String [] args) {  
       Clock c = new Clock;  
    
       c.setTime("12345")  
       String tod = c.getTime();  
       System.out.println(time: " + tod);  
     }
    }  
    

    When you run the program, program starts in mains,

    1. object c is created
    2. function setTime() is called by the object c
    3. the variable time is set to the value passed by
    4. function getTime() is called by object c
    5. the time is returned
    6. It will passe to tod and tod get printed out

提交回复
热议问题