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("访问内部类构造方法");
        }
    }
  • 相关阅读:
    23.课程应用接口
    22.课程页面设计
    21.手机接口
    20.云通讯
    19.JWT
    18.权限认证
    解决github下载慢的终极方法
    vs code 配置c/c++环境
    Python 字符编码处理总结
    Python编码
  • 原文地址:https://www.cnblogs.com/spadd/p/4172767.html
Copyright © 2011-2022 走看看