【java】重写方法的一些注意点

静态方法不能被重写,非静态方法才能被子类重写。

public class Person {
    public static void f1(){
        System.out.println("person static f1");
    }
    public void f2(){
        System.out.println("person f2");
    }
}
public class Student extends Person{
    public static void f1(){
        System.out.println("student static f1");
    }
    public void f2() {
        System.out.println("student f2");
    }
}
public class Test {
    public static void main(String[] args) {
        Student student = new Student();
        student.f1();
        student.f2();
        System.out.println("-----------------------");
        Person person = new Student();
        person.f1();
        person.f2();
    }
}

上述代码结果如下

image-20211231232428789

可以这样思考。static 方法是类方法,当我们调用 static 方法时是看引用所属的类是哪个,而不是看 new 的对象是谁。上述中 person 引用是通过 Person 类声明的,故调用的是 Person 类的 static 方法。

而非静态方法是要有具体的对象才能使用,所以是和对象绑定的,由于两次都是通过 Student类 创建对象,所以调用的非静态方法的 Student 里的非静态方法。

此外 子类还不能重写父类中的 final 方法、private方法。

成员字段不能像方法一样被重写。当子类定义具有相同名称的字段时,该子类仅声明一个新字段。超类中的字段是隐藏的。它没有被重写,所以它不能被多态访问。可以通过 super.字段名 访问父类的字段。

posted @ 2021-12-31 23:28  hzyuan  阅读(76)  评论(0)    收藏  举报