super在java中是干什么的
时间: 2024-06-13 22:00:30 浏览: 134
在Java中,super关键字用于访问父类中的属性和方法。当子类和父类中有同名的属性或方法时,使用super关键字可以区分是调用父类的还是子类的属性或方法。此外,当子类需要在重写父类方法时,可以使用super关键字来调用父类的方法,然后在此基础上进行扩展。
以下是super关键字的几种用法:
1. 访问父类的属性和方法
```java
public class Parent {
public String name = "Parent";
public void sayHello() {
System.out.println("Hello from Parent");
}
}
public class Child extends Parent {
public String name = "Child";
public void sayHello() {
super.sayHello(); // 调用父类的sayHello方法
System.out.println("Hello from Child");
}
public void printName() {
System.out.println(super.name); // 访问父类的name属性
System.out.println(this.name); // 访问子类的name属性
}
}
Child child = new Child();
child.sayHello(); // 输出:Hello from Parent Hello from Child
child.printName(); // 输出:Parent Child
```
2. 调用父类的构造方法
```java
public class Parent {
public Parent(String name) {
System.out.println("Parent's name is " + name);
}
}
public class Child extends Parent {
public Child(String name) {
super(name); // 调用父类的构造方法
System.out.println("Child's name is " + name);
}
}
Child child = new Child("Tom"); // 输出:Parent's name is Tom Child's name is Tom
```
3. 在接口中使用super关键字
```java
public interface MyInterface {
default void sayHello() {
System.out.println("Hello from MyInterface");
}
}
public class MyClass implements MyInterface {
@Override
public void sayHello() {
MyInterface.super.sayHello(); // 调用接口中的sayHello方法
System.out.println("Hello from MyClass");
}
}
MyClass myClass = new MyClass();
myClass.sayHello(); // 输出:Hello from MyInterface Hello from MyClass
```
阅读全文
相关推荐


















