[英]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.