Java中静态函数的隐藏

在Java中,如果派生类静态函数的名称与基类静态函数相同,则基类静态函数会隐藏派生类静态函数。例如,以下Java代码打印 “A.乐趣() 注意:静态方法是一个类属性,因此如果从具有类容器的类名或对象调用静态方法,则该类的方法将被调用,而不是对象的方法。

null

JAVA

// file name: Main.java
// Parent class
class A {
static void fun() { System.out.println( "A.fun()" ); }
}
// B is inheriting A
// Child class
class B extends A {
static void fun() { System.out.println( "B.fun()" ); }
}
// Driver Method
public class Main {
public static void main(String args[])
{
A a = new B();
a.fun(); // prints A.fun();
// B a = new B();
// a.fun(); // prints B.fun()
// the variable type decides the method
// being invoked, not the assigned object type
}
}


输出

A.fun()

注: 如果我们将A.fun()和B.fun()都设为非静态,那么上面的程序将打印“B.fun()”。虽然这两种方法都是静态类型,但变量类型决定调用的方法,而不是指定的对象类型 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享