简体   繁体   English

使用相同命名的静态方法创建多个类

[英]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().由于两个类都有同名的静态方法,我想创建一个类似于父元素的东西,它们将与之相关,声明它的所有子元素都将实现一个静态方法 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.要由子类实现,name() 方法应该是抽象的。 Which isn't possible as it is static.这是不可能的,因为它是静态的。 Also study about the implications of inheriting static methods : Are static methods inherited in Java?还要研究继承静态方法的含义: Java 中是否继承了静态方法

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

相关问题 实现相同接口的多个类的方法相同 - Same method for multiple classes that implement the same interface Java设计模式:多个类上的相同方法 - Java design pattern: same method on multiple classes 如何将相同的方法添加到多个类(活动) - How to add same method to multiple classes (activity) 使用相同静态方法的多个无状态Bean - Multiple Stateless Beans using same static method 使静态方法同步或不同步 - Making static method Synchronized or Not Java外部和内部类的方法名称相同:非静态方法静态上下文错误 - Java outer and inner classes have method with the same name: non-static method static context error 有没有更好的方法来实现我在多个类中使用的 static 方法? - Is there a better way to implement static method that I use in multiple classes? 当(在 Java 中)static 方法和具有相同名称的实例方法存在于不同的类中时,我无法访问该方法 - When (in Java) a static method and an instance method with the same name exist in different classes, I cannot access the method 在静态方法中使用getActivity() - Making use of getActivity() in a static method 为什么静态类字段不会与其他方法变量(以相同名称命名)发生冲突 - Why static class fields don't collide with other method variables (named with same name)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM