乐闻世界logo
搜索文章和话题

What is the difference between this and super keyword in Java?

1 个月前提问
1 个月前修改
浏览次数15

1个答案

1

在Java中,this关键字和super关键字都非常重要,它们在处理类及其超类(父类)的实例时起着关键的作用。下面是这两个关键字的主要区别和使用场景:

  1. 定义和用途

    • this关键字 用于引用当前对象的实例。它可以用来访问当前类中的变量、方法和构造函数。
    • super关键字 用于引用当前对象的超类(父类)。它主要用于访问超类中的变量、方法和构造函数。
  2. 访问属性

    • 使用 this 可以访问当前类中定义的字段(属性),即使这些字段被超类中的同名字段隐藏也是如此。
    • 使用 super 则可以访问隐藏在子类中的超类字段。

    示例

    java
    class Parent { int value = 10; } class Child extends Parent { int value = 20; void display() { // 访问Child类的value属性 System.out.println(this.value); // 输出20 // 访问Parent类的value属性 System.out.println(super.value); // 输出10 } }
  3. 调用方法

    • this 可以用来调用当前类中的其他方法。
    • super 用来调用超类中的方法,这在方法重写(Override)时特别有用,当子类需要扩展而不是完全替代父类方法的功能时。

    示例

    java
    class Parent { void show() { System.out.println("Parent method"); } } class Child extends Parent { void show() { super.show(); // 调用Parent类的show方法 System.out.println("Child method"); } }
  4. 构造函数

    • this() 构造函数调用用于调用同一个类中的其他构造函数。
    • super() 构造函数调用用于调用父类的构造函数。在子类构造器中,super()必须是第一个语句。

    示例

    java
    class Parent { Parent() { System.out.println("Parent Constructor"); } } class Child extends Parent { Child() { super(); // 调用Parent的构造函数 System.out.println("Child Constructor"); } }

综上所述,thissuper 关键字在Java编程中提供了访问和控制类及其层次结构的强大工具,能够使代码更加清晰、有组织且易于管理。

2024年8月16日 00:58 回复

你的答案