创建个人类Person,再以该类为父类创建一个学生子类 Student, 定义一个主类Demo。
时间: 2024-11-03 20:15:47 浏览: 30
在Java中,我们可以首先定义一个名为`Person`的基本类,然后创建一个名为`Student`的子类,它是`Person`类的特化版本。`Student`通常会添加一些特定于学生的属性和方法。接着,我们会定义一个`Demo`主类来演示如何实例化这两个类并展示多态。
```java
// 定义基础类 Person
public class Person {
private String name;
private int age;
// 构造函数
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 简单的 getter 和 setter 方法
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; }
// 具体的行为,例如打招呼
public void sayHello() {
System.out.println("Hello, my name is " + name);
}
}
// 子类 Student 继承自 Person 并增加特有的属性和行为
public class Student extends Person {
private String school;
public Student(String name, int age, String school) {
super(name, age); // 调用父类构造函数
this.school = school;
}
// 添加学生特有的方法,如学习
public void study() {
System.out.println(name + " is studying at " + school);
}
// 重写父类的 sayHello 方法,提供更具体的问候
@Override
public void sayHello() {
System.out.println("Hi, I'm a student named " + name + " from " + school);
}
}
// 主类 Demo
public class Demo {
public static void main(String[] args) {
// 创建普通Person对象
Person person = new Person("Alice", 30);
person.sayHello(); // 输出: Hello, my name is Alice
// 创建Student对象,并显示多态效果
Student student = new Student("Bob", 20, "XYZ University");
student.sayHello(); // 输出: Hi, I'm a student named Bob from XYZ University
student.study(); // 输出: Bob is studying at XYZ University
// 通过父类引用调用子类方法
Person studentAsPerson = (Person) student;
studentAsPerson.sayHello(); // 输出: Hi, I'm a student named Bob from XYZ University
}
}
```
阅读全文