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

相关推荐
一晌小贪欢几秒前
Python爬虫第7课:多线程与异步爬虫技术
开发语言·爬虫·python·网络爬虫·python爬虫·python3
普通网友几秒前
KUD#73019
java·php·程序优化
番茄Salad5 分钟前
自定义Spring Boot Starter项目并且在其他项目中通过pom引入使用
java·spring boot
ftpeak10 分钟前
《Cargo 参考手册》第二十二章:发布命令
开发语言·rust
程序员三明治17 分钟前
详解Redis锁误删、原子性难题及Redisson加锁底层原理、WatchDog续约机制
java·数据库·redis·分布式锁·redisson·watchdog·看门狗
luckyPian24 分钟前
学习go语言
开发语言·学习·golang
自由的疯26 分钟前
Java 怎么学习Kubernetes
java·后端·架构
自由的疯27 分钟前
Java kubernetes
java·后端·架构
祁同伟.1 小时前
【C++】多态
开发语言·c++
普通网友1 小时前
IZT#73193
java·php·程序优化