從頭認識java-8.4 內部類與向上轉型

來源:互聯網
上載者:User

從頭認識java-8.4 內部類與向上轉型

這一章節我們來討論一下內部類與向上轉型。

跟普通的類一樣,內部類也可以實現某個介面然後向上轉型。

為什嗎?

因為這樣能夠更好的隱藏實現的細節,基本其他程式員使用繼承來擴充介面和方法都不能訪問相關實現。

 

package com.ray.ch03;public class Test {private class Person implements CanRun {@Overridepublic void run() {System.out.println(run);}}public Person getPerson() {return new Person();}public static void main(String[] args) {CanRun person = new Test().getPerson();person.run();}}interface CanRun {void run();}

上面的代碼通過了介面,完全隔絕了實現與介面的依賴,完全隱藏了實現的細節。

 

上面的代碼即便我通過繼承Test來擴充,但是由於Test所有的實現方法都是private的,因此,是不會有任何重寫的方法。

 

package com.ray.ch03;public class Test {private class Person implements CanRun {@Overridepublic void run() {System.out.println(run);}}public Person getPerson() {return new Person();}public static void main(String[] args) {CanRun person = new Test().getPerson();person.run();}}class myTest extends Test {//沒有任何需要重寫的方法}interface CanRun {void run();}

我們再來看一個例子:

 

 

package com.ray.ch03;public class Test {private class Ship implements Destination {private String destination = abc;@Overridepublic String read() {return destination;}}public Ship destination() {return new Ship();}public static void main(String[] args) {Destination destination = new Test().destination();destination.read();}}class myTest extends Test {// 沒有任何需要重寫的方法}interface Destination {String read();}


 

總結:這一章節主要討論了內部類與向上轉型,通過介面把實現完全隱藏起來。

 

 

聯繫我們

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