Java - 你能在Java中覆盖静态方法吗?如果在子类中创建相同的方法会产生编译错误么?

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程

不能,你不能在Java中覆盖静态方法,但可以在子类中声明一个完全相同的方法,不会产生编译错误,这在Java中称为方法隐藏。

你不能覆盖Java中的静态方法,因为方法覆盖基于运行时的动态绑定,静态方法在编译时使用静态绑定进行绑定。虽然可以在子类中声明一个具有相同名称和方法签名的方法,看起来可以在Java中覆盖静态方法,但实际上这是方法隐藏。Java不会在运行时解析方法调用,并且根据调用静态方法的Object类型,将调用相应的方法。这意味着如果你使用父类的类型来调用静态方法,那么静态方法将从父类中调用;另一方面如果你使用子类的类型来调用静态方法,则会调用来自子类的方法。简而言之,你无法在Java中覆盖静态方法。

package chimomo.learning.java.code.staticmethod;

/**
 * Java program which demonstrate that we can not override static method in Java. 
 *
 * @author Created by Chimomo
 */
public class CanWeOverrideStaticMethod {
    public static void main(String[] args) {
        Screen screen = new ColorScreen();

        // If we can override static method, this should call method from child class.
        // IDE will show warning, static method should be called from classname.
        screen.show();
    }
}

/* ------ Running Results ------
Static method from parent class
*/
package chimomo.learning.java.code.staticmethod;

/**
 * @author Created by Chimomo
 */
public class Screen {
    /**
     * public static method which can not be overridden in Java
     */
    public static void show() {
        System.out.print("Static method from parent class");
    }
}
package chimomo.learning.java.code.staticmethod;

/**
 * @author Created by Chimomo
 */
public class ColorScreen extends Screen {
    /**
     * Static method of same name and method signature as existed in super class,
     * this is not method overriding instead this is called method hiding in Java. 
     */
    public static void show() {
        System.err.println("Overridden static method in Child Class in Java");
    }
}

此运行结果确认无法覆盖Java中的静态方法,并且静态方法基于类型信息而不是基于Object进行绑定。我们不能覆盖静态方法,我们只能在Java中隐藏静态方法。创建具有相同名称和方法签名的静态方法称为Java隐藏方法。IDE将显示警告:“静态方法应该使用类名而不是使用对象来调用”, 因为静态方法不能在Java中重写。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值