Java 程序中 super() 和 this() 的区别
javaobject oriented programmingprogramming更新于 2025/7/22 0:44:17
除了其他各种关键字之外,Java 还提供了 this 和 super 作为特殊关键字,主要分别用于表示类的当前实例及其超类。这两个关键字之间有显著的差异,如下所示 -
| Sr.不。 | 关键 | this | super |
|---|---|---|---|
| 1 | 表示和引用 | this 关键字主要表示类的当前实例。 | 另一方面,super 关键字表示父类的当前实例。 |
| 2 | 与类构造函数的交互 | this 关键字用于调用相同的默认构造函数类。 | super 关键字用于调用父类的默认构造函数。 |
| 3 | 方法可访问性 | 此关键字用于访问当前类的方法,因为它具有当前类的引用。 | 可以借助 super 关键字访问父类的方法。 |
| 4 | 静态上下文 | 此关键字可从静态上下文引用,即可从静态实例调用。例如,我们可以编写 System.out.println(this.x),它将打印 x 的值而不会产生任何编译或运行时错误。 | 另一方面,super 关键字不能从静态上下文引用,即不能从静态实例调用。例如,我们不能编写 System.out.println(super.x),这将导致编译时错误。 |
此关键字与 super 的示例
Equals.jsp
class A {
public int x, y;
public A(int x, int y) {
this.x = x;
this.y = y;
}
}
class B extends A {
public int x, y;
public B() {
this(0, 0);
}
public B(int x, int y) {
super(x + 1, y + 1);// 调用父类构造函数
this.x = x;
this.y = y;
}
public void print() {
System.out.println("Base class : {" + x + ", " + y + "}");
System.out.println("Super class : {" + super.x + ", " + super.y + "}");
}
}
class Point {
public static void main(String[] args) {
B obj = new B();
obj.print();
obj = new B(1, 2);
obj.print();
}
}
输出
Base class : {0, 0}
Super class : {1, 1}
Base class : {1, 2}
Super class : {2, 3}
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

