zoukankan      html  css  js  c++  java
  • java 内部类的继承

    Think in Java P268

    因为内部类构造必须关联到外部类的引用,所以主要问题是如何构建派生类构建一个外部类的引用。

    public class InheritInner extends WithInner.Inner{
        InheritInner(WithInner wi) {
            wi.super();
        }
    }
    class WithInner
    {
        class Inner
        {
    
        }
    }

    关键代码,在内部类派生中,传入外部类的引用,并使用外部类的引用.super()方法。

    如果没有wi.super() 报错,no enclosing instance type of  ,没有封闭的实例类型

    那么这个wi.super()真正的作用是什么呢。

    public class Computer {
    
        int model;
    
        Computer(int i) {
            model = i;
        }
    
        public class HardDrive {
            int size;
    
            public HardDrive(int i) {
                size = i;
            }
    
            public HardDrive() {
                size = 40;
            }
            @Override
            public String toString() {
                return "HardDrive    size  "+size;
            }
        }
    
        @Override
        public String toString() {
            return "Computer    model  "+model;
        }
    
        public static void main(String[] args) {
            Computer computer = new Computer(10);
            SCSI   scsi = new SCSI(computer);
    System.out.println(computer); System.out.println(scsi.size); } }
    class SCSI extends Computer.HardDrive { SCSI(Computer c) { c.super(80); } }

    输出结果:

    Computer model 10
    80

    我们知道,实例子对象时,父类的对象也会实例化。

    所以例子中 Computer.HardDrive 也会被实例化,而且是带参数的实例化,输出的结果也表明了它被正确的实例化了。

    所以我猜测Object.super()的作用是把HardDrive实例化了

  • 相关阅读:
    Python
    Python
    Python
    Python
    Python
    《The Rise and Fall of Scala》scala的兴衰
    Scala核心编程_第05章_函数式编程
    IntelliJ IDEA scala的源码设置
    Scala核心编程_第04章 程序流程控制
    Scala核心编程_第03章_运算符
  • 原文地址:https://www.cnblogs.com/alway-july/p/7513761.html
Copyright © 2011-2022 走看看