zoukankan      html  css  js  c++  java
  • java 内部类和向上转型

    当将内部类向上转型为其基类时,尤其是转型为一个接口的时候,内部类就有了用武之地,(从实现某个接口的对象,得到对接口的引用,与向上转型为这个对象的基类,实际上是一样的效果,),这是因为此内部类---某个接口的实现---能够完全不可见,并且不可用,所得到的只是指向基类或接口的引用,所以能够很方便地隐藏实现细节

    //: innerclasses/Destination.java
    package object;
    public interface Destination {
      String readLabel();
    } ///:~
    //: innerclasses/Contents.java
    package object;
    public interface Contents {
      int value();
    } ///:~
    //: innerclasses/TestParcel.java
    package object;
    class Parcel4 {
      private class PContents implements Contents { //private类除了直接外部类parcel4,没人可以访问
        private int i = 11;
        public int value() { return i; }
      }
      protected class PDestination implements Destination {//protect类只有直接外部类及其子类可以访问,还有同一个包的可以访问
        private String label;
        private PDestination(String whereTo) {
          label = whereTo;
        }
        public String readLabel() { return label; }
      }
      public Destination destination(String s) {
        return new PDestination(s);
      }
      public Contents contents() {
        return new PContents();
      }
    }
    
    public class TestParcel {
      public static void main(String[] args) {
        Parcel4 p = new Parcel4();
        Contents c = p.contents();
        Destination d = p.destination("Tasmania");
        // Illegal -- can't access private class:
        //! Parcel4.PContents pc = p.new PContents();
      }
    } ///:~
  • 相关阅读:
    python 装饰器
    python 环境迁移之requirements.txt (window环境)
    selenium 元素查找与属性
    pytest+allure(allure-pytest基于这个插件)设计定制化报告
    Capability配置
    python_excel
    python_连接mysql
    MySql_1
    appium_环境搭建
    appium_appium简介
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10219521.html
Copyright © 2011-2022 走看看