zoukankan      html  css  js  c++  java
  • 內部类向上转型为接口

    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("访问内部类构造方法");
        }
    }
  • 相关阅读:
    51 Nod 1068 Bash游戏v3
    51 Nod Bash 游戏v2
    51 Nod 1073 约瑟夫环
    UVA 12063 Zeros and ones 一道需要好好体会的好题
    51 Nod 1161 Partial sums
    2018中国大学生程序设计竞赛
    UVA 11971 Polygon
    UVA 10900 So do you want to be a 2^n-aire?
    UVA 11346 Possibility
    python with as 的用法
  • 原文地址:https://www.cnblogs.com/spadd/p/4172767.html
Copyright © 2011-2022 走看看