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();
      }
    } ///:~
  • 相关阅读:
    软考笔记(二)
    软件工程笔记
    安卓反编译
    [转] 扫描二维码自动区分下载Android或者iOS
    git使用技巧总结
    利用iTunes给MP3添加专辑插图
    Flex弹性盒子中`flex-grow`,`flex-shrink`,`flex-basis`的区别
    Android 中Activity和Fragment的启动顺序
    Java 类加载的过程
    Android Studio 查看源码出现throw new RuntimeException("Stub!"); 解决办法
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10219521.html
Copyright © 2011-2022 走看看