java中get和set方法的理解与使用

之前看到java中经常出现一堆相对应的set和get,简单的知道set是传值get是取值。

例如:

books.java

 1 package test.testxml;
 2 
 3 public class books {
 4     private int id;
 5     private String name;
 6     private double price;
 7     private String author;
 8     
 9     
10     public int getId() {
11         return id;
12     }
13     public void setId(int id) {
14         this.id = id;
15     }
16     public String getName() {
17         return name;
18     }
19     public void setName(String name) {
20         this.name = name;
21     }
22     public double getPrice() {
23         return price;
24     }
25     public void setPrice(double price) {
26         this.price = price;
27     }
28     public String getAuthor() {
29         return author;
30     }
31     public void setAuthor(String author) {
32         this.author = author;
33     }
34 }    

一个books的类中有几个私有的成员变量(private的成员变量只能被与自己在同一个类中的方法访问)

那么其他类中的方法想要访问怎么办呢?这个时候就是通过set和get方法来访问的。

例子:

test01.java

public class test01 {
    public static void main(String[] args) {     
                books b=new books();
               b.setAuthor("JiaRui");
        System.out.println(b.getAuthor());  
}              

输出的内容就是set进去的内容“JiaRui”。

 

posted @ 2016-04-17 19:38  Rui_Jia  阅读(1832)  评论(0编辑  收藏  举报