Discuss / Java / 练习笔记

练习笔记

Topic source

The__Wolf

#1 Created at ... [Delete] [Delete and Lock User]

1、注意ps是student类型的变量,它指向的是PrimaryStudent类型的实例

2、ps可以调用Student类里对应的方法,而不能直接调用PrimaryStudent类里有而Student类里没有的方法,如果要调用,需要向下转型

3、如果Student类里有和PrimaryStudent类里相同的方法但是内容不同,例如下面的talk()方法,用ps直接调用则会执行PrimaryStudent里的对应talk(),衔接了后面的多态。

public class Main {    public static void main(String[] args) {        Person p = new Person("小明", 12);        Student s = new Student("小红", 20, 99);        // TODO: 定义PrimaryStudent,从Student继承,新增grade字段:        Student ps = new PrimaryStudent("小军", 9, 100, 5);        System.out.println(ps.getScore());        System.out.println(((PrimaryStudent) ps).getGrade());        ps.talk();    }}class Person {    protected String name;    protected int age;    public Person(String name, int age) {        this.name = name;        this.age = age;    }    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; }}class Student extends Person {    protected int score;    public Student(String name, int age, int score) {        super(name, age);        this.score = score;    }    public int getScore() { return score; }    public void talk() {System.out.println("student!");}}class PrimaryStudent extends Student{    protected int grade;    public PrimaryStudent(String name, int age, int score, int grade){        super(name, age, score);        this.grade = grade;    }    public int getGrade() { return grade; }    public void talk() {System.out.println("primary student!");}}

  • 1

Reply