对于以下代码:
public class NewClass {
public static class superclass {
static void print()
{
System.out.println("print in superclass.");
}
}
public static class subclass extends superclass {
static void print()
{
System.out.println("print in subclass.");
}
}
public static void main(String[] args)
{
superclass A = new superclass();
superclass B = new subclass();
A.print();
B.print();
}
}
这里B.print()
打印-->“在父类(super class)中打印。”,但我希望它打印“在子类中打印”。因为“B”是子类的对象。
但是,如果我将 static void print()
更改为 void print()
,那么它会正确打印“print in subclass.`”。
有人可以帮助理解这一点吗?
最佳答案
我们可以在子类中声明具有相同签名的静态方法,但它不被视为重写,因为不会有任何运行时多态性。
如果派生类定义了与基类中的静态方法具有相同签名的静态方法,则派生类中的方法将隐藏基类中的方法。
/* Java program to show that if static method is redefined by
a derived class, then it is not overriding. */
// Superclass
class Base {
// Static method in base class which will be hidden in subclass
public static void display() {
System.out.println("Static or class method from Base");
}
// Non-static method which will be overridden in derived class
public void print() {
System.out.println("Non-static or Instance method from Base");
}
}
// Subclass
class Derived extends Base {
// This method hides display() in Base
public static void display() {
System.out.println("Static or class method from Derived");
}
// This method overrides print() in Base
public void print() {
System.out.println("Non-static or Instance method from Derived");
}
}
// Driver class
public class Test {
public static void main(String args[ ]) {
Base obj1 = new Derived();
// As per overriding rules this should call to class Derive's static
// overridden method. Since static method can not be overridden, it
// calls Base's display()
obj1.display();
// Here overriding works and Derive's print() is called
obj1.print();
}
}
Output:
Static or class method from Base
Non-static or Instance method from Derived
以下是 Java 中方法重写和静态方法的一些要点。
1)对于类(或静态)方法,根据引用的类型来调用方法,而不是根据所引用的对象来调用方法,这意味着方法的调用是在编译时决定的。
2)对于实例(或非静态)方法,该方法是根据所引用的对象的类型来调用的,而不是根据引用的类型来调用,这意味着方法的调用是在运行时决定的。
3) 实例方法不能重写静态方法,静态方法不能隐藏实例方法。例如,以下程序有两个编译器错误。
4) 在子类(或派生类)中,我们可以重载从父类(super class)继承的方法。此类重载方法既不隐藏也不重写父类(super class)方法——它们是新方法,对于子类来说是唯一的。
关于java - 继承类之间的静态方法 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59170455/