18、內部類向上轉型為介面

來源:互聯網
上載者:User

標籤:style   blog   ar   color   sp   div   log   bs   ad   

package com.lei.duixiang;/** * 內部類向上轉型為介面 * 1、非內部類不能被聲明為 private 或 protected 訪問類型 * 2、從執行結果可以看出,這條語句執行的是內部類中的f() 方法 *        很好地對繼承該類的子類隱藏了實現細節,僅為編寫子類的人留下一個介面和一個外部類 *   同時也可以調用f() 方法,但是 f()方法的具體實現過程卻很好的被隱藏了,這是內部類最基本的用途 * @author Administrator * */interface OutInterface{    //定義一個介面    public void f();}public class InterfereInner {    public static void main(String[] args) {        OutClass2 out = new OutClass2();    //執行個體化一個 OutClass2對象        // 調用 doit() 方法,返回一個 OutInterface 介面        OutInterface outInterface =  out.doit();        outInterface.f();    //調用 f() 方法    }}class OutClass2{     //定義一個內部類實現 OutInterface介面    private class InnerClass implements OutInterface{        InnerClass(String s){    //構造方法            System.out.println(s);        }                public void f() {    //實現介面中的f()方法            System.out.println("訪問內部類的 f() 方法");        }            }        public OutInterface doit(){    //定義一個方法,傳回值類型為 outInterface 介面        return new InnerClass("訪問內部類構造方法");    }}

 

18、內部類向上轉型為介面

聯繫我們

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