[英]Why can I not have an abstract and static method in the same class in Java
I have the following class: 我有以下课程:
public abstract class A
{
public abstract String doSomething(String X, String Y);
public static String doSomething(String X, String Y){return X + Y;}
...
}
The issue I have is that the static and abstract doSomething()
methods seem to clash as duplicates. 我遇到的问题是静态和抽象的doSomething()
方法似乎是重复的。 I thought this should be fine because the static method belongs to the class, not an instance of the class, so I was going to use the abstract method to enforce the method on all subclasses and the static method as a helper so that I have nicely factored code. 我认为这应该没问题,因为静态方法属于类,而不是类的实例,因此我将使用抽象方法在所有子类上强制执行该方法,并将静态方法作为帮助程序,以便我很好地使用因子代码。
I know I could probably add an interface into the mix, but I don't really understand what's wrong with my abstract and static methods existing on the same class. 我知道我可能会在混合中添加一个接口,但我真的不明白我在同一个类上存在的抽象和静态方法有什么问题。 What's wrong with this? 这有什么问题?
In Java it is valid (despite being misleading and confusing) to call a static method from an object instance rather than the class name (despite warnings generated by many compilers). 在Java中,从对象实例调用静态方法而不是类名称(尽管许多编译器生成警告 )是有效的(尽管有误导性和混淆)。
System.out.println(String.valueOf(true)); // Prints "true".
System.out.println("".valueOf(true)); // Prints "true", unfortunately.
So the following seemingly valid code wouldn't know which of those methods to call: 所以下面看似有效的代码不知道要调用哪些方法:
A a = getInstanceOfConcreteSubclassOfA();
a.doSomething(null, null); // Compiler can't decide which method to call...
Unfortunately, it's just one of the few ugly corners of the Java language. 不幸的是,它只是Java语言中为数不多的几个角落之一。
It's not specific to abstract methods; 它并不特定于抽象方法; in general, Java doesn't let you have two methods with the same parameter-types but one being static and one not. 通常,Java不允许您使用相同参数类型的两个方法,但一个是静态的而一个不是。 Something like this: 像这样的东西:
public String doSomething(String X, String Y){return X + Y;}
public static String doSomething(String X, String Y){return X + Y;}
would also be illegal. 也是非法的。
(This makes sense when you consider that you're allowed to call a static method "on" an actual instance, or for that matter, on any expression of the appropriate type. The compiler translates ((A)null).staticMethod()
to A.staticMethod()
.) (当你考虑允许在一个实际的实例上调用一个静态方法,或者就此而言,在任何相应类型的表达式上调用静态方法时,这是有道理的。编译器转换((A)null).staticMethod()
到A.staticMethod()
。)
Each method has a signature composed of: 每种方法都有一个签名组成:
method name
parameter type
Return type
If 2 methods have the same signature, this will cause an error. 如果2个方法具有相同的签名,则会导致错误。
the word static
does not interfere in the signature of the method just like const
. 字static
不一样的方法的签名干扰const
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.