java筆記14之private

來源:互聯網
上載者:User

標籤:成員方法   turn   java筆記   .sh   show   set   div   student   不能   

private:
        1 是一個許可權修飾符
        2 可以修飾成員變數和成員方法
        被其修飾的成員只能在本類中被訪問

 1 class Demo { 2     //int num = 10; 3     //用private修飾 4     private int num = 10; 5      6     public void show() { 7         System.out.println(num); 8     } 9     10     private void method() {11         System.out.println("method");12     }13     14     public void function() {15         method();16     }17 }18 19 class PrivateDemo {20     public static void main(String[] args) {21         Demo d = new Demo();22         //不能方法私人的成員變數23         //System.out.println(d.num);24         d.show();25         //不能訪問私人的成員方法26         //d.method();27         d.function();28     }29 }

封裝和private的應用:
        A:把成員變數用private修飾
        B:提高對應的getXxx()和setXxx()方法

 1 class Student { 2     //姓名 3     private String name; 4     //年齡 5     private int age; 6      7     //姓名擷取值 8     public String getName() { 9         return name;10     }11     12     //姓名設定值13     public void setName(String n) {14         name = n;15     }16     17     //年齡擷取值18     public int getAge() {19         return age;20     }21     22     //年齡賦值23     public void setAge(int a) {24         age = a;25     }26 }27 28 //測試類別29 class StudentTest {30     public static void main(String[] args) {31         //建立學生對象32         Student s = new Student();33         34         //使用成員變數35         //錯誤:被私人修飾了,外界不能直接存取了36         //System.out.println(s.name+"---"+s.age);37         System.out.println(s.getName()+"---"+s.getAge());38         39         //給成員變數賦值40         //s.name = "林青霞";41         //s.age = 27;42         //通過方法給賦值43         s.setName("林青霞");44         s.setAge(27);45         System.out.println(s.getName()+"---"+s.getAge());46     }47 }

 

java筆記14之private

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.