繁体   English   中英

在另一个函数中创建子类的实例时,为什么不能从子类类型的 Abstact 类调用方法(公共或静态)?

[英]Why can't I call a method (public or static) from an Abstact class of type subclass when creating an instance of the subclass in another function?

在下面的代码中,找不到类型为 Dollar 的函数 Dollar 并且程序无法编译:

    class Test{
      abstract class Money{
        protected int amount;
        public Dollar dollar(int amount){
          return new Dollar(amount);
        }
    }

    class Dollar extends Money{
      public Dollar(int amount){
        this.amount= amount;
      }
    }

    public void testMultiplication(){
      Money d = new Money.dollar(5);
    }

    public static void main(String args[]){}
}
    
    

我已经使用以下命令在 cli 上启动了我的 java 应用程序:

java File.java 

以下是警告内容:

File.java:16: error: cannot find symbol
        Money d = new Money.dollar(5);
                       ^
  symbol:   class dollar
  location: class Test.Money
1 error
error: compilation failed 

该代码引用自 Kent Beck 编写的 Test-Driven Development By Example 一书。 还有一个 github,其中包含我用作指南的更完整的代码: https : //github.com/No3x/money-tdd-by-example-kent-beck/blob/master/src/main/java/de /no3x/tdd/money/Money.java

我想提一下,抽象类 Money 中的函数 Dollar Dollar 也被指示为静态的,但这会在我们正在处理的当前错误之上创建另一个错误。

阅读上述内容后,您是否明白为什么在另一个函数中创建对象的实例时,我不能从类型为子类的 Abstact 类中调用方法(公共或静态)?

  • abstract class Money :您正在声明一个抽象类 Money。
  • Money d = new Money.dollar(5); :然后您尝试使用new关键字从此类实例化一个对象。 这对于抽象类是不允许的。

如果要从外部调用抽象类中定义的方法,则它必须是static方法,然后静态调用此方法。 这是您的代码的重构版本。

class Test {

   abstract static class Money {

    protected int amount;

    public static Dollar dollar(int amount) {
      return new Test().new Dollar(amount);
    }
  }

  class Dollar extends Money {

    public Dollar(int amount) {
      this.amount = amount;
    }
  }

  public void testMultiplication() {
    Money d = Money.dollar(5);
  }

  public static void main(String args[]) {}
}

TLDR:这段代码有很多问题,如果它是从书中复制的,那么我建议您从头开始。 问题不在于抽象类。

问题:

首先, Money d = new Money.dollar(5); 不是有效的语法。 如果方法 A 创建了一个 B 类型的新对象,你应该写: B justCreated = A(); (丢失new )。

除此之外:在您的版本中抽象类 Money 中的函数 Dollar Dollar 也被指示为 static ),由于 Dollar 是非静态的,因此您不能使用Money.dollar()

如果它是静态的,它仍然不起作用(如您所说),因为您不能在非静态内部类中创建静态方法,因此 Money 也必须是静态的。 但是你不能在静态方法中使用new (见这个线程)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM