Java关于类的继承中方法重写的坑

类的继承中方法重写需要保证方法为非静态方法,若为静态方法会出现以下问题。

现象演示

正常非静态方法:

public class Father {

    public void test(){
        System.out.println("I'm father");
    }

}
public class Son extends Father {

    public void test(){
        System.out.println("I'm son");
    }

}
public static void main(String[] args) {
    Father a = new Son();
    a.test();

    Son b = new Son();
    b.test();
}

运行结果:

此时为我们所熟悉的方法重写,指向的对象都为Son,此时调用的是Son中的test方法。

若为静态方法:

public class Father {

    public static void test(){
        System.out.println("I'm father");
    }

}
public class Son extends Father {

    public static void test(){
        System.out.println("I'm son");
    }

}
public static void main(String[] args) {
    Father a = new Son();
    a.test();

    Son b = new Son();
    b.test();
}

运行结果:

此时我们发现,方法的调用只和接收时定义的数据类型有关,Father类型只会调用Father中的test方法,Son类型只会调用Son中的test方法。

结论

当类的继承中的方法是非静态方法,此时子类中对父类方法进行重写,用父类的引用指向子类对象并调用该方法,实际调用的是重写后的方法。

当其为静态方法时,实际上不算是方法重写,此时方法的调用只和左边定义的数据类型有关。

posted @ 2020-07-14 19:10  Karber  阅读(6)  评论(0)    收藏  举报