JAVA 复写

子类对introduce进行复写

public class Person {

    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println("Person 二参构造");
    }

    void introduce() {
        System.out.println("我的名字是" + name + ", 我的年龄是" + age);
    }
}
public class Student extends Person {

    String address;

    public Student(String name, int age, String address) {
        super(name, age);
        this.address = address;
    }

    void introduce() {
        System.out.println("我的名字是" + name + ", 我的年龄是" + age + ", 我的地址是" + address);
    }

}
public class Test {

    public Test() {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Student student = new Student("furong", 12, "BeiJing");
        student.introduce();
    }

}

运行结果

Person 二参构造
我的名字是furong, 我的年龄是12, 我的地址是BeiJing

子类改进

public class Student extends Person {

    String address;

    public Student(String name, int age, String address) {
        super(name, age);
        this.address = address;
    }

    void introduce() {
        super.introduce();
        System.out.println("我的地址是" + address);
    }

}
原文地址:https://www.cnblogs.com/zhangxuechao/p/13595584.html