首页 > 解决方案 > 我们可以覆盖静态方法吗?为什么输出是这样的?

问题描述

class Base {

    public static void display() {
        System.out.println("Static or class method from Base");
    }

    public void print() {
        System.out.println("Non-static or Instance method from Base");
    }
}

class Derived extends Base {

    public static void display() {
        System.out.println("Static or class method from Derived");
    }

    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();
        obj1.display();
        obj1.print();
    }
}

此代码的输出显示 -

Static or class method from Base
Non-static or Instance method from Derived

谁能解释一下为什么会这样??

标签: javaoverriding

解决方案


推荐阅读