• 代码查错1


    修改:

    interface Playable {
      void play();
    }
    interface Bounceable {
      void play();
    }
    interface Rollable extends Playable, Bounceable {
      Ball ball = new Ball("PingPang");
    }
    class Ball implements Rollable {
      private String name;
      public String getName() {
        return name;
      }
      public Ball(String name) {
        this.name = name;     
      }
      public void play() {
        ball = new Ball("Football");
        System.out.println(ball.getName());
      }
    }
    这个错误不容易发现。
    答案错。"interface Rollable extends Playable, Bounceable"没有问题。interface可继承多个interfaces,所以这里没错。问题出在interface Rollable里的"Ball ball = new Ball("PingPang");"任何在interface里声明的interface variable (接口变量,也可称成员变量),默认为public static final。也就是说"Ball ball = new Ball("PingPang");"实际上是"public static final Ball ball = new Ball("PingPang");"。在Ball类的Play()方法中,"ball = new Ball("Football");"改变了ballreference,而这里的ball来自Rollable interfaceRollable interface里的ballpublic static final的,finalobject是不能被改变reference的。因此编译器将在"ball = new Ball("Football");"这里显示有错。

  • 相关阅读:
    spring-boot4
    spring-boot3代码
    spring-boot3
    spring-boot2代码
    spring-boot2
    Java Socket编程
    eclipse项目中.classpath文件详解
    spring-boot1
    ASCII 在线转换器
    如何在Android开发中让你的代码更有效率
  • 原文地址:https://www.cnblogs.com/chengbao/p/4840823.html
Copyright © 2020-2023  润新知