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

相关推荐
一只特立独行的猪6111 小时前
Java面试——集合篇
java·开发语言·面试
大得3692 小时前
go注册中心Eureka,注册到线上和线下,都可以访问
开发语言·eureka·golang
讓丄帝愛伱2 小时前
spring boot启动报错:so that it conforms to the canonical names requirements
java·spring boot·后端
weixin_586062022 小时前
Spring Boot 入门指南
java·spring boot·后端
小珑也要变强3 小时前
队列基础概念
c语言·开发语言·数据结构·物联网
Dola_Pan5 小时前
Linux文件IO(二)-文件操作使用详解
java·linux·服务器
wang_book5 小时前
Gitlab学习(007 gitlab项目操作)
java·运维·git·学习·spring·gitlab
AI原吾5 小时前
掌握Python-uinput:打造你的输入设备控制大师
开发语言·python·apython-uinput
机器视觉知识推荐、就业指导5 小时前
Qt/C++事件过滤器与控件响应重写的使用、场景的不同
开发语言·数据库·c++·qt
毕设木哥5 小时前
25届计算机专业毕设选题推荐-基于python的二手电子设备交易平台【源码+文档+讲解】
开发语言·python·计算机·django·毕业设计·课程设计·毕设