封裝隱藏了類的內部實現機制,能夠在不影響使用的狀況下改變類的內部結構,同時也保護了數據。對外界而已它的內部細節是隱藏的,暴露給外界的只是它的訪問方法。ide
public class Student { public Student(String name, Integer age) { this.name = name; this.age = age; } private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
getter方法禁止返回可變對象的引用,可變對象引用會破壞封裝(下面演示錯誤的使用封裝方法)this
public class Student { public Student(Date birthday) { this.birthday = birthday; } private Date birthday; public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } } class Main{ public static void main(String[] args) { Student student = new Student(new Date()); System.out.println("student對象的Date:"+student.getBirthday());//student對象的Date:Tue Dec 11 10:50:50 CST 2018 Date birthday = student.getBirthday(); birthday.setTime(888888888); System.out.println("student對象的Date:"+student.getBirthday());//student對象的Date:Sun Jan 11 14:54:48 CST 1970 } }
經過繼承建立的新類稱爲「子類」或「派生類」,被繼承的類稱爲「基類」、「父類」或「超類」。繼承的過程,就是從通常到特殊的過程。繼承概念的實現方式有二類:實現繼承與接口繼承。實現繼承是指直接使用基類的屬性和方法而無需額外編碼的能力;接口繼承是指僅使用屬性和方法的名稱、可是子類必須提供實現的能力;編碼
public class Student extends People { } class People{ void sayHello(){ System.out.println("Hello Word"); } } class Main{ public static void main(String[] args) { Student student = new Student(); student.sayHello(); } }
一個對象變量能夠指向多種實際類型的現象被成爲多態;在運行時可以自動選擇調用那個方法被稱爲動態綁定.code
public class Student extends People { @Override void sayHello(){ System.out.println("I am a Student"); } void studentHello(){ System.out.println("It is student Say"); } } class Teacher extends People{ } class People{ void sayHello(){ System.out.println("Hello Word"); } } class Main{ public static void main(String[] args) { People people1 = new Teacher(); People people2 = new Student(); people1.sayHello(); people2.sayHello(); ((Student) people2).studentHello(); } }
要實現多態必須存在繼承關係(student和teacher都繼承people)對象
子類須要將父類的方法重寫(繼承已經默認重寫),若是重寫了父類方法則會使用重寫方法繼承
須要將子類的引用賦值給父類,這樣父類變量就能夠調用非子類特有方法接口
父類引用不能夠賦值給子類變量,若是必須須要;能夠使用強制類型轉換,強制類型轉換會暫時忽略對象的實際類型,使用對象的所有功能get
Student student = (Student) new People();