为什么Java中同一个类中不能有抽象方法和静态方法
我有以下课程:
public abstract class A
{
public abstract String doSomething(String X, String Y);
public static String doSomething(String X, String Y){return X + Y;}
...
}
我遇到的问题是静态和抽象 doSomething() 方法似乎因重复而发生冲突。我认为这应该没问题,因为静态方法属于类,而不是类的实例,所以我打算使用抽象方法在所有子类上强制执行该方法,并将静态方法作为辅助方法,这样我就可以很好地因式分解的代码。
我知道我可能可以在组合中添加一个接口,但我真的不明白同一个类上存在的抽象方法和静态方法有什么问题。这有什么问题吗?
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. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Java 中,从对象实例而不是类名调用静态方法是有效的(尽管会产生误导和混淆)(尽管许多编译器会生成警告)。
因此,以下看似有效的代码将不知道要调用这些方法中的哪一个:
不幸的是,它只是 Java 语言中为数不多的丑陋角落之一。
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).
So the following seemingly valid code wouldn't know which of those methods to call:
Unfortunately, it's just one of the few ugly corners of the Java language.
它并不特定于抽象方法;一般来说,Java 不允许您拥有两种具有相同参数类型的方法,但一种是静态的,另一种不是。像这样的事情:
也是非法的。
(当您认为您可以在实际实例“上”调用静态方法,或者就此而言,在适当类型的任何表达式上调用静态方法时,这是有意义的。编译器会翻译
((A)null)。 staticMethod()
到A.staticMethod()
。)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. Something like this:
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()
toA.staticMethod()
.)每个方法都有一个签名,其组成如下:
如果两个方法具有相同的签名,则会导致错误。
static
一词不会干扰方法的签名,就像const
一样。Each method has a signature composed of:
If 2 methods have the same signature, this will cause an error.
the word
static
does not interfere in the signature of the method just likeconst
.