java中super和this的用法代码实现
时间: 2024-03-06 17:49:26 浏览: 17
下面是使用Java代码演示super和this关键字的用法:
```java
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
void sayHello() {
System.out.println("Hello, I'm " + name + ", " + age + " years old.");
}
}
class Student extends Person {
String school;
Student(String name, int age, String school) {
super(name, age); // 调用父类的构造方法
this.school = school;
}
void study() {
System.out.println(name + " is studying at " + school + ".");
}
void sayHello() {
super.sayHello(); // 调用父类的方法
System.out.println("I'm a student.");
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Tom", 18, "ABC School");
s.sayHello(); // 调用子类的方法
s.study(); // 调用子类的方法
}
}
```
在上面的代码中,Person是一个父类,Student是一个子类。在Student的构造方法中,使用super关键字调用了父类的构造方法,以初始化父类的成员变量。在子类中,重写了父类的方法sayHello,并使用super关键字调用了父类的方法。在子类中还定义了一个自己的方法study,用来演示子类的成员方法。在Main类中,创建了一个Student对象s,并调用了它的成员方法。