java封裝學習

來源:互聯網
上載者:User

標籤:system   實現   其他   學習   ima   string   介面   資訊   img   

封裝:將類的某些資訊隱藏在類內部,不允許外部程式直接存取,而是通過該類提供的方法來實現對隱藏資訊的操作和訪問。把過程和資料包圍起來,對資料的訪問只能通過已定義的介面。

在java中通過關鍵字private實現封裝。

需要用特定的方法來進行屬性的讀寫:getter setter

首先瞭解未封裝的函數容易被其他類改變其屬性值。

1 public class Test {2      String name="張三";            //參量沒有用private修飾3     public void ss(){  //擷取屬性值4         System.out.println(name);5     }6 }

 

1 public class Test2 {2     public static void main(String[] args){3         Test test=new Test();4         test.name="李四";5         test.ss();6     }    7 }

運行顯示結果為:

李四

說明屬性值已經被Test2改變

如果將Test類中的name屬性加上private修飾

編譯環境報錯,說明該屬性不能被本類以外的類調用。

那封裝之後的類通過什麼方法來改便其屬性值呢?

答案就是setter和getter

 1 public class Test { 2    private  String name="張三";            //參量用private修飾 3     public void ss(){  //擷取屬性值 4         System.out.println(name); 5     } 6     public String getName(){ 7         return name; 8     } 9     public void setName(String newName){10         name=newName;11     }12 }
1 public class Test2 {2     public static void main(String[] args){3         Test test=new Test();4         test.setName("李四");5         System.out.println("名字為:"+test.getName());6         test.getName();7     }    8 }

顯示結果為:

名字為:李四

 

java封裝學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.