Java中的继承与多态

Java · 前天 · 6 人浏览

java中的继承代表实例化一个子类,子类依旧可以调用父类的方法和属性,可以省去子类单独编写一些重复代码,例如eat、sleep这种,还有一些通用方法啊,在父类设置后直接子类继承,很方便。多态是指,针对某个类型的方法调用,其真正执行的方法取决于运行时期实际类型的方法。下面是关于继承与多态相关的代码:

public class Main {
    public static void main(String[] args) {
        Person p = new Student();


        System.out.println(p.num); //返回 1
        p.run(); //返回 Student.run 不论加不加 override 只要是父类声明的非static方法,子类也有的同名方法,都会调用子类的方法。
        System.out.println(p.name); //返回 jack
        // System.out.println(p.type); // 报错 因为引用了不在引用类型中的变量。
        // p.run2(); // 报错 要调用它,需要向下转型为`Student`。通过父类引用调用方法时,该方法必须在父类中声明(否则编译报错)



        // 由此可以看出,首先寻找的num是根据编译时类型来定位的。
        // 而调用方法则是从实例出发,调用的是实例的Student方法,但限制为必须是在父类也有的同名方法。
    }
}

class Person {
    protected int num = 1;
    protected String name = "jack";
    public void run() {
        System.out.println("Person.run");
    }
}

class Student extends Person {
    protected int type = 1;

    protected int num = 2;
    @Override
    public void run() {
        System.out.println("Student.run");
    }
    
    public void run2() {
        System.out.println("run2");
    }
}

总结:
2025-06-04T21:59:32.png
2025-06-04T22:00:13.png

本站立足于美利堅合衆國,請讀者自覺遵守當地法律!如有違規,本站不承擔任何法律責任! This site is based in the United States of America, readers are requested to abide by local laws! If there are any violations, this site does not bear any legal responsibility! Theme Jasmine by Kent Liao