gir*_*iri 58 java static overriding overloading
我想知道:
ope*_*sas 77
静态方法不能在单词的确切意义上被覆盖,但它们可以隐藏父静态方法
在实践中,这意味着que编译器将决定在编译时执行哪个方法,而不是在运行时,就像重写实例方法一样.
有一个简洁的例子,请看这里.
而这是Java文档解释之间的区别重写实例方法和隐藏的类(静态)方法.
覆盖:在Java中覆盖只是意味着将根据对象的运行时类型调用特定方法,而不是根据它的编译时类型调用(覆盖静态方法的情况)
隐藏:静态的父类方法不是子类的一部分(尽管它们是可访问的),因此不存在覆盖它的问题.即使您在子类中添加另一个静态方法,与其父类中的静态方法相同,此子类静态方法也是唯一的,并且与其父类中的静态方法不同.
Vol*_*eam 25
静态方法不能被覆盖,因为没有什么可以覆盖,因为它们是两种不同的方法.例如
static class Class1 {
public static int Method1(){
return 0;
}
}
static class Class2 extends Class1 {
public static int Method1(){
return 1;
}
}
public static class Main {
public static void main(String[] args){
//Must explicitly chose Method1 from Class1 or Class2
Class1.Method1();
Class2.Method1();
}
}
Run Code Online (Sandbox Code Playgroud)
是的静态方法可以像任何其他方法一样重载.
Thi*_*ilo 10
无法覆盖静态方法,因为它们在运行时未在对象实例上调度.编译器决定调用哪个方法.
这就是您在编写时收到编译器警告的原因
MyClass myObject = new MyClass();
myObject.myStaticMethod();
// should be written as
MyClass.myStaticMethod()
// because it is not dispatched on myObject
myObject = new MySubClass();
myObject.myStaticMethod();
// still calls the static method in MyClass, NOT in MySubClass
Run Code Online (Sandbox Code Playgroud)
静态方法可以重载(意味着只要它们具有不同的参数类型,您可以为多个方法使用相同的方法名称).
Integer.parseInt("10");
Integer.parseInt("AA", 16);
Run Code Online (Sandbox Code Playgroud)
静态的父类方法不是子类的一部分(尽管它们是可访问的),因此不存在覆盖它的问题.即使您在子类中添加另一个静态方法,与其父类中的静态方法相同,此子类静态方法也是唯一的,并且与其父类中的静态方法不同.