Discuss / Java / 练习

练习

Topic source

韦雪松

#1 Created at ... [Delete] [Delete and Lock User]
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());
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

class Student extends Person {
    private int score;

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

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
}

class PrimaryStudent extends Student {
    private int grade;

    public PrimaryStudent(String name, int age, int score, int grade) {
        super(name, age, score);
        this.grade = grade;
    }

    public int getGrade() {
        return grade;
    }
}

just

#2 Created at ... [Delete] [Delete and Lock User]
getGrade()

这个没用到啊

□▼□

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

@just 

虽然getGrade()没有用到,但是grade是个private级别的字段,我们一般希望可以通过get方法获取它的值,以及用set方法安全的修改它.

这里的属性都定义为private是错误的 大家注意

@是胡不是霍

这里的属性都定义为private是不建议的  后面的子类都无法继承父类的属性  大家注意

NOTA

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

@是胡不是霍

是不是在JAVA编程中类里面的字段名都应该统一用

protected 

修饰


  • 1

Reply