android studio定义一个子类Student,继承Person类,并写一个main(),实现对该子类及其父类的调用
时间: 2023-12-21 17:03:57 浏览: 79
好的,下面是实现的代码:
```java
// Person类
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void sayHello() {
System.out.println("Hello, my name is " + name + ". I'm " + age + " years old.");
}
}
// 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 saySchool() {
System.out.println("I'm studying at " + school);
}
}
// 主函数
public class Main {
public static void main(String[] args) {
Person person = new Person("Lucy", 20);
person.sayHello();
Student student = new Student("Tom", 18, "Beijing University");
student.sayHello();
student.saySchool();
}
}
```
运行上述代码,输出如下:
```
Hello, my name is Lucy. I'm 20 years old.
Hello, my name is Tom. I'm 18 years old.
I'm studying at Beijing University
```
可以看出,子类Student继承了父类Person的方法和属性,并且还添加了自己的方法和属性。在主函数中,我们分别创建了一个Person对象和一个Student对象,并调用它们的方法。
阅读全文