【问题标题】:Play Framework 2.1.0 not seeing static method from derived classPlay Framework 2.1.0 看不到派生类的静态方法
【发布时间】:2013-06-29 23:34:58
【问题描述】:

我将Play Framework 2.1.0Java 一起使用,遇到了一个我不太理解的奇怪错误。

我在包models.entitiesAnimal.java中有一个基类,它定义了一个公共静态方法List<AnimalType> getAllCows(),如下图:

package models.entities;

public class Animal {
     public static List<Cow> getAllCows() {}
}

然后我有一个扩展 Animal 的类:

package models;

public class Cow extends Animal {

}

从我的 Scala 模板 show_animals.scala.html,我可以调用以下内容:

models.entities.Animal.getAllCows()

但是当我尝试使用扩展类调用静态方法时,报错如下:

Cow.getAllCows()

value getAllCows is not a member of object models.Cows

在我看来它应该可以工作,但它没有......我错过了什么吗?

谢谢!

【问题讨论】:

    标签: java scala inheritance playframework-2.0


    【解决方案1】:

    静态方法只属于声明它的。因为只有 Animal 类定义了它,所以 Cow.getAllCows() 会引发错误。您可以将其视为通过 namespace(其类名)访问的全局方法。 instance 方法的继承方式(具有多态性)不适用于静态方法。

    这个概念有点难以理解,因为如果你要编写下面的 Cow 类,它会起作用。

    public class Cow extends Animal {
         public static List<Cow> getCows() {
             return getAllCows(); // inherited; or some prefer visible
         }
    }
    

    所以,如果您将代码更改为

    public class Animal {
         public static List<Cow> getAllCows() {
             System.out.println("Animal.getAllCows() invoked");
         }
    }
    
    public class Cow extends Animal {
         public static List<Cow> getAllCows() {
             System.out.println("Cow.getAllCows() invoked");
             return Animal.getAllCows();
         }  
    }
    

    Cow.getAllCows() 可以重复使用 base 类实现。

    但是,请注意,这不会为您提供多态性。您只是重新实现了(base 类的)方法,也称为method-hiding。因此,如果您要运行以下命令

    Animal animal = new Cow();
    animal.getAllCows(); // would print: Animal.getAllCows() invoked
    

    【讨论】:

      猜你喜欢
      • 2013-06-27
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 2010-10-10
      • 2012-06-25
      • 2013-01-10
      • 1970-01-01
      相关资源
      最近更新 更多