JAVA--类的继承

继承

Main.java

package ex02;

public class Main {
    public static void main(String[] args) {
        Person p1 = new Person();
        Person p2 = new Student();
        System.out.println(p1 instanceof Student);
        System.out.println(p2 instanceof Student);
    }
}

Person.java

package ex02;

public class Person {

    protected String name;
    protected int age;

    //默认构造方法
    public Person(){

    }


    //自定义构造方法
    public Person(String name ,int age){
        this.age=age;
        this.name=name;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Student.java

package ex02;

public class Student extends ex02.Person{
    protected double grade;

    //默认构造方法
    public Student(){

    }

    //自定义构造方法
    public Student(String name , int age,double grade){
        super();
        this.grade=grade;
    }

    public double getGrade() {
        return grade;
    }

    public void setGrade(double grade) {
        this.grade = grade;
    }

    public String msg(){
        return name+","+age + ","+grade;
    }
}

你可能感兴趣的:(JAVA,java)