Java物件導向基本特徵

來源:互聯網
上載者:User

標籤:java

1、封裝性

    一個對象和外界的聯絡應當通過一個統一的介面,應當公開的公開,應當隱藏的隱藏。

    屬性的封裝:Java中類的屬性的存取權限的預設值是default,要想隱藏該屬性或方法,就可以加private(私人)修飾符,來限制只能夠在類的內部進行訪問。對於類中的私人屬性,要對其給出一對方法(getXxx(),setXxx())訪問私人屬性,保證對私人屬性的操作的安全性。 

    方法的封裝:對於方法的封裝,該公開的公開,該隱藏的隱藏。方法公開的是方法的聲明(定義),即(只須知道參數和傳回值就可以調用該方法),隱藏方法的實現會使實現的改變對架構的影響最小化。

public class TestDemo {public static void main(String[] args) {Person person=new Person();person.tell();person.setAge(-20);person.setName("張三");person.tell();}}class Person{private int age;private String name;public int getAge() {return age;}public void setAge(int age) {if(age>0&&age<150){this.age = age;}}public String getName() {return name;}public void setName(String name) {this.name = name;}void tell(){System.out.println("姓名:"+name+";年齡:"+age);}}

備忘:(1)Java匿名對象:只需要使用一次的場所。例如:new Person().tell();

      (2)Java構造方法:構造方法名稱必須與類名一致,沒有返回指,可以重載,主要為類中的屬性初始化。

      (3)值傳遞的資料類型:八種基礎資料型別 (Elementary Data Type)和String(String也是傳遞的地址,只是String對象和其他對象是不同的,String是final的,所以String對象值是不能被改變的,值改變就會產生新對象。那麼StringBuffer就可以了,但只是改變其內容,不能改變外部變數所指向的記憶體位址)。

           引用傳遞的資料類型:除String以外的所有複合資料型別,包括數組、類和介面。

public class TestRef4 {public static void main(String args[])  {    int val=10;;    StringBuffer str1, str2;        str1 = new StringBuffer("apples");    str2 = new StringBuffer("pears");        System.out.println("val:" + val);    System.out.println("str1 is " + str1);    System.out.println("str2 is " + str2);     System.out.println("...............................");        modify(val, str1, str2);      System.out.println("val is " + val);    System.out.println("str1 is " + str1);    System.out.println("str2 is " + str2);  }   public static void modify(int a, StringBuffer r1,StringBuffer r2)  {            a = 0;      r1 = null;              r2.append(" taste good");      System.out.println("a is " + a);      System.out.println("r1 is " + r1);      System.out.println("r2 is " + r2);      System.out.println("...............................");  }}

輸出結果為:

val:10str1 is applesstr2 is pears...............................a is 0r1 is nullr2 is pears taste good...............................val is 10str1 is applesstr2 is pears taste good


2、繼承性










本文出自 “IT技術學習與交流” 部落格,謝絕轉載!

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.