1. 程式人生 > >Java中的面向物件、繼承與介面(封裝)

Java中的面向物件、繼承與介面(封裝)

Java面向物件程式設計有四(三)大特性:繼承、封裝、多型、(抽象)。今天就從這三個方面進行學習。

最簡單的思路,首先,繼承,封裝,多型是什麼意思,然後要了解到,他們到底有什麼用。每一項設計都是有意義,有作用的,知道為什麼用,有什麼用,才能更好的理解。(這點有人總結的很好,what, why, how)

1、封裝

What?

GeeksforGeeks:Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. Other way to think about encapsulation is, it is a protective shield that prevents the data from being accseed by the code outside this shield.

概念:簡單來說,封裝就跟其字面意思一樣,是將東西包裝起來。那麼包裝的是什麼呢?用什麼包裝起來呢?可以理解為用一個類,在這個類中我們把類中的變數和資料封裝起來,讓外界無法訪問,也看不到。只有這個類自身的方法可以訪問這些變數和資料。在封裝中,別的類是無法看到這個封裝好的類中的資料的,這種情況也叫作data-binding,(資料是封裝類中的資料,可以理解為把資料(data),還有類(code)bind在一起了)。

Why?

1. data hiding:封裝之後,使用者是不知道類的內部實現的。使用者只知道我們使用setter方法傳進去一個值並且這個值會被初始化而已。(類的內部使用者不可見)

2.Increased Flexibiliy: 增加了靈活性。我們可以通過封裝,很簡單的把類當做(read only)或者(write only)的。不提供set就是read only,不提供get就是write only。而且當有需求要求改變我們的setter方法的時候,我們只需要改變setter方法就可以了。

3.測試和維護很簡單。通過封裝,就像我們建立了一個一個盒子一樣,這樣當我們做unit test的時候會更加簡單。同時,因為程式碼都被封裝為不同的unit, 當application中某一部分需要改變的時候,我們直接改變那個unit就可以,不會影響到其他的不分。

4.Reusable:封裝好的程式碼可以被一個application或者across mutiple application重用。比如說我們建立了一個class,並且對他進行好了封裝,在整個application的生命週期中,或者當其他的application需要相同的class的時候,我們都可以直接reuse這個class來例項化得到我們需要的物件。

How?

大致來說,在java中封裝有幾種實現的方法。

介面(封裝所有的行為),類,access modifiers(訪問修飾符?中文應該是這麼叫),方法中的setter還有getter(與modifiers一同使用)

具體例子可見自己的程式碼。

other:(http://www.codejava.net/java-core/the-java-language/what-is-encapsulation-in-java-the-what-why-and-how)

Encapsulation vs. Abstraction

So far you got a proper understanding about abstraction and encapsulation in Object-Oriented Programming with Java. To summary:
  • Abstraction is the process of modeling real things in the real word into programming language. In Java, the process of abstraction is done using interfaces, classes, abstract classes, fields, methods and variables. Everything is an abstraction.
  • Encapsulation is the process of hiding information details and protecting data and behavior of an object from misuse by other objects. In Java, encapsulation is done using access modifiers (public, protected, private) with classes, interfaces, setters, getters.

The Truth About Abstraction in Java

  • Abstraction is not about interfaces or abstract classes. Abstraction is the progress of modeling real world objects into programming language. Hence interfaces and abstract classes are just two techniques used in this progress.
  • In an Object-Oriented Programming language like Java, everything is an abstraction: interface, class, field, method, variable, etc.
  • Abstraction is the fundamental concept on which other concepts rely on: encapsulation, inheritance and polymorphism

面試中可能會出現的考察點(如果之後遇到了,可以回來更新這篇部落格):

這個部分過於基礎,可能面試中的考察並不多,大部分是在考察別的方面時,順便考察。