this和super关键字在Java中有什么作用?

this和super关键字在Java中有什么作用


文章目录


前言

this 和 super 是 Java 中的两个关键字,它们在面向对象编程中起着重要的作用。它们用于引用当前对象或其父类对象。


一、this 关键字

this 关键字用于引用当前对象。它的主要用途有以下几点:

  1. 引用当前对象的属性:当方法的参数或局部变量与类的成员变量重名时,可以使用 this 来区分它们。
java 复制代码
public class MyClass {  
    int value;  
  
    public void setValue(int value) {  
        this.value = value; // 使用 this 引用当前对象的 value 属性  
    }  
  
    public int getValue() {  
        return this.value; // 使用 this 引用当前对象的 value 属性  
    }  
}
  1. 在构造器中调用另一个构造器:一个构造器可以使用 this() 来调用另一个构造器。
java 复制代码
public class MyClass {  
    int x, y;  
  
    public MyClass() {  
        this(1, 2); // 调用带有两个参数的构造器  
    }  
  
    public MyClass(int x, int y) {  
        this.x = x;  
        this.y = y;  
    }  
}
  1. 在方法中引用当前对象本身:在某些情况下,你可能需要引用当前对象本身,例如在某些设计模式或事件处理中。
java 复制代码
public class MyClass {  
    public void doSomething() {  
        MyClass obj = this; // 将当前对象引用赋值给另一个变量  
        // ... 使用 obj 进行操作 ...  
    }  
}

二、super 关键字

super 关键字用于引用父类对象。它的主要用途有以下几点:

  1. 调用父类的构造器:子类构造器可以使用 super() 来调用父类的构造器。
java 复制代码
class Parent {  
    public Parent() {  
        System.out.println("Parent constructor called");  
    }  
}  
  
class Child extends Parent {  
    public Child() {  
        super(); // 调用父类的构造器  
        System.out.println("Child constructor called");  
    }  
}  
  
public class Main {  
    public static void main(String[] args) {  
        Child child = new Child(); // 输出: Parent constructor called, Child constructor called  
    }  
}
  1. 访问父类的属性或方法:当子类与父类有同名的属性或方法时,可以使用 super 来引用父类的属性或方法。
java 复制代码
class Parent {  
    int value = 10;  
  
    public void showValue() {  
        System.out.println("Parent value: " + value);  
    }  
}  
  
class Child extends Parent {  
    int value = 20;  
  
    public void showValue() {  
        super.showValue(); // 调用父类的 showValue 方法  
        System.out.println("Child value: " + this.value); // 使用 this 引用子类的 value 属性  
    }  
}  
  
public class Main {  
    public static void main(String[] args) {  
        Child child = new Child();  
        child.showValue(); // 输出: Parent value: 10, Child value: 20  
    }  
}

相关推荐
雪的季节几秒前
Qt 自定义表头
开发语言·qt
huipeng926几秒前
企业级微服务开发实战(三):公共模块设计与统一规范封装
java·spring boot·spring cloud·微服务·架构·系统架构·php
我登哥MVP6 分钟前
Spring Boot 从“会用”到“精通”:参数绑定体系全景
java·spring boot·spring·servlet·maven·intellij-idea·mybatis
C137的本贾尼9 分钟前
JDBC 编程:用 Java 连接 MySQL
java·开发语言·mysql
AI视觉网奇12 分钟前
three-bvh-csg glb分割
开发语言·前端·javascript
牢姐与蒯14 分钟前
c++数据结构之c++11(二)
开发语言·c++
华大哥15 分钟前
spring boot 和php 调用 LibreOffice 转换 Excel 到 PDF 完整实现
java·pdf·excel
z2005093017 分钟前
【linux学习】深入理解 Linux 进程间通信:管道的艺术与实现
linux·开发语言
lcj251118 分钟前
【stack、queue、deque、priority_queue】C++ 栈 / 队列 / 优先级队列全解析!手撕实现 + 二叉树层序遍历(附源码)
开发语言·c++·笔记
微风欲寻竹影19 分钟前
Java数据结构——二叉树相关OJ题目详解
java·数据结构