简体   繁体   中英

Making multiple classes with the same named static method

Imagine having the classes:

public class classA {
  public static String name() {
    return "classA";
  }
}
public class classB {
  public static String name() {
    return "classB";
  }
}

Since both classes have the same-named static method, I would like to make something like a parent element that they would relate to that would declare that all its child would implement a static method name().

Using interfaces is impossible since I don't want the declaration of the static method to be inside the interface and static methods cannot be overridden. Also, using an abstract class is also not a solution since I can't declare an abstract static method.

Is there a way of doing what I would want to?

您不能使用 static 关键字强制执行父子关系,因此没有办法做到这一点。

To be implemented by a child class, name() method should be abstract. Which isn't possible as it is static. Also study about the implications of inheriting static methods : Are static methods inherited in Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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