gpt4 book ai didi

java - 继承类之间的静态方法 - Java

转载 作者:行者123 更新时间:2023-11-30 07:39:44 24 4
gpt4 key购买 nike

对于下面的代码:

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)方法——它们是新方法,是子类独有的。

Source

关于java - 继承类之间的静态方法 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59170455/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com