Java中this和super的使用
本文记录下在Java中, this 和 super 是两个关键字,作用是用于引用当前对象和父类对象。
1. this
this 关键字用于引用当前对象
,主要有以下用途:
- 当方法的
参数名和实例变量名相同
时,可以使用 this 关键字来区分 - 在构造方法中
调用其他构造方法
:通过 this() 来调用同一个类中的其他构造方法。 - 返回当前对象:在方法中
返回当前对象
的引用。
2. super 关键字:
- super 关键字用于引用父类对象,可以在
子类中
使用。 - 主要用有:
- 调用
父类构造方法
,通过 super() 来调用父类的构造方法。 - 访问
父类的成员变量和方法
,可以使用 super 关键字来访问父类的成员变量和方法。 - 在子类中
重写
父类方法时,使用super 来调用父类的方法
。
- 调用
Java示例代码:
class Parent {
String name;
public Parent(String name) {
this.name = name;
}
public void display() {
System.out.println("Parent Name: " + this.name);
}
}
class Child extends Parent {
int age;
public Child(String name, int age) {
super(name); // 调用父类构造方法
this.age = age;
}
public void display() {
super.display(); // 调用父类方法
System.out.println("Child Age: " + this.age);
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child("Alice", 10);
child.display();
}
}
总结
this 关键字用于引用当前对象的成员变量, super 关键字用于调用父类的构造方法和方法。通过 this 和 super 关键字,可以方便地访问当前对象和父类对象的成员。
希望对看到本文的你有帮助。
上一篇 java面向对象三大特征 |
记得点赞收藏哦!!!
| 下一篇 Java静态代理和动态代理详解 |