super和this有什么区别
时间: 2023-11-09 19:04:30 浏览: 41
在Java中,super和this关键字都用于访问对象的属性和方法,但它们有不同的用途。
1. super关键字
super关键字用于在子类中访问父类的属性和方法。在子类中,如果父类和子类有同名的属性或方法,则使用super关键字可以区分它们。
例如:
```
class Parent {
int x = 10;
void print() {
System.out.println("Parent");
}
}
class Child extends Parent {
int x = 20;
void print() {
super.print(); // 调用父类的print方法
System.out.println("Child");
System.out.println(super.x); // 访问父类的x属性
System.out.println(this.x); // 访问子类的x属性
}
}
```
2. this关键字
this关键字用于在当前对象中访问属性或方法。它通常用于区分局部变量和实例变量,或者用于在构造函数中调用其他构造函数。
例如:
```
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name; // 使用this关键字区分局部变量和实例变量
this.age = age;
}
Person(String name) {
this(name, 0); // 调用另一个构造函数
}
}
```