我相信你们都知道我的意思 - 代码例如:
Thread thread = new Thread();
int activeCount = thread.activeCount();
引发编译器警告。为什么不是错误呢?
EDIT:
需要明确的是:问题与线程无关。我意识到在讨论这个问题时经常会给出线程的例子,因为它们可能会把事情搞砸。但真正的问题是这样的用法是always胡言乱语,你不能(有能力)写出这样的电话并认真执行。这种类型的方法调用的任何例子都是愚蠢的。这是另一个:
String hello = "hello";
String number123AsString = hello.valueOf(123);
这使得每个 String 实例看起来都带有一个“String valueOf(int i)”方法。
基本上我相信Java设计者在设计该语言时犯了一个错误,并且由于涉及兼容性问题而修复它为时已晚。是的,它可能会导致非常具有误导性的代码。是的,你应该避免它。是的,您应该确保您的 IDE 配置为将其视为错误,IMO。如果您自己设计一种语言,请记住它作为要避免的事情的示例:)
为了回应 DJClayworth 的观点,以下是 C# 中允许的内容:
public class Foo
{
public static void Bar()
{
}
}
public class Abc
{
public void Test()
{
// Static methods in the same class and base classes
// (and outer classes) are available, with no
// qualification
Def();
// Static methods in other classes are available via
// the class name
Foo.Bar();
Abc abc = new Abc();
// This would *not* be legal. It being legal has no benefit,
// and just allows misleading code
// abc.Def();
}
public static void Def()
{
}
}
为什么我觉得它有误导性?因为如果我看代码someVariable.SomeMethod()
我希望它能使用的值someVariable
. If SomeMethod()
是静态方法,该期望无效;代码在欺骗我。这怎么可能是一个good thing?
奇怪的是,Java 不允许您使用可能未初始化的变量来调用静态方法,尽管事实上它将使用的唯一信息是变量的声明类型。这是一个不一致且无益的混乱。为什么允许呢?
编辑:此编辑是对 Clayton 答案的回应,该答案声称它允许静态方法的继承。事实并非如此。静态方法不是多态的。这是一个简短但完整的程序来证明这一点:
class Base
{
static void foo()
{
System.out.println("Base.foo()");
}
}
class Derived extends Base
{
static void foo()
{
System.out.println("Derived.foo()");
}
}
public class Test
{
public static void main(String[] args)
{
Base b = new Derived();
b.foo(); // Prints "Base.foo()"
b = null;
b.foo(); // Still prints "Base.foo()"
}
}
如您所见,执行时间值b
被完全忽略。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)