6

Java中静态函数的隐藏遮蔽

 9 months ago
source link: https://www.jdon.com/71141.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Java中静态函数的隐藏遮蔽

在 Java 中,静态方法不会像实例方法那样被重载或重写。相反,它们是被隐藏了。

对于静态方法:

  • 所调用的方法是在编译时根据引用类型而不是对象的运行时类型确定的。这种行为被称为方法隐藏。
  • 从类名或有类容器的对象调用静态方法时,调用的是类的方法,而不是对象的方法。

Java 中的静态函数隐藏是指在同一作用域中有两个同名的静态方法:

  • 第一个方法被称为第二个方法的影子。
  • 第二个方法在被调用时将优先于第一个方法。

让我们看一个例子来说明这一点:

class Parent {
    static void staticMethod() {
        System.out.println("Static method in Parent");
    }
}

class Child extends Parent {
    static void staticMethod() {
        System.out.println("Static method in Child");
    }
}

public class Main {
    public static void main(String[] args) {
        Parent.staticMethod(); // Calls staticMethod() in Parent class
        Child.staticMethod();  // Calls staticMethod() in Child class

Parent parentReference = new Child();
        parentReference.staticMethod(); // 调用父类中的 staticMethod()
    }
}

在这个例子中:

  • Parent有一个名为 的静态方法staticMethod。
  • Child有一个名称相同但实现不同的静态方法。
调用 Parent.staticMethod() 会调用父类中的静态方法。同样,调用 Child.staticMethod() 会调用子类中的静态方法。

但是,如果使用超类的引用来引用子类的对象(Parent parentReference = new Child();),然后调用 parentReference.staticMethod(),它仍然会调用父类中的静态方法。这是因为静态方法不能像实例方法那样被重写

  • 在普通的方法重载中,如果超类和子类具有相同签名的方法,则这两个方法都可供子类的对象使用。执行的方法取决于对象引用的类型。
  • 对于静态方法,由于它们不属于任何实例,因此可以使用类名来访问它们。如果超类和子类具有相同签名的静态方法,则子类方法将隐藏超类方法。

总之:
静态方法不可能被覆盖,因为静态方法是在编译时解析的。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK