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  
    }  
}

相关推荐
yeki_3031 分钟前
jmeter定时器-Constant Throughput Timer
java·开发语言·jmeter
天龙拳2 小时前
为什么EasyExcel能处理大数据量而不内存溢出,EasyExcel原理
java
他人是一面镜子,保持谦虚的态度2 小时前
零、ubuntu20.04 安装 anaconda
开发语言·python
抓饼先生2 小时前
bash中如何区分系统命令和自定义函数
开发语言·bash
程序员JerrySUN2 小时前
观察者模式详解:用 Qt 信号与槽机制深入理解
开发语言·qt·观察者模式
cfjybgkmf2 小时前
Python列表2
开发语言·python
lina_mua2 小时前
JavaScript 中的性能优化:从基础到高级技巧
开发语言·javascript·性能优化
范哥来了2 小时前
python 游戏开发cocos2d库安装与使用
开发语言·python·cocos2d
冰红茶兑滴水2 小时前
Qt 导入TagLib库
开发语言·qt
Answer_ism4 小时前
【SpringMVC】SpringMVC拦截器,统一异常处理,文件上传与下载
java·开发语言·后端·spring·tomcat