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();
      }
    } ///:~
  • 相关阅读:
    msysgit 上传文件夹,规范化的日常
    第三次作业【补完作业】
    c++我在努力----第三次作业体会
    编程题
    视频课程作业随笔
    HDU 4123 Bob’s Race 树形dp+单调队列
    HDU 4514 湫湫系列故事——设计风景线 树的直径
    POJ 1239 Increasing Sequences 动态规划
    BNUOJ 52318 Be Friends prim+Trie
    HDU 5925 Coconuts 离散化
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10219521.html
Copyright © 2011-2022 走看看