this和super区别

this 和 super 都是 Java 中关键词,用于在类中访问当前对象或父类对象的属性和方法。它们的使用方式和作用不同,下面我们来详细了解一下它们的区别。

this

this 关键字主要用于表示当前对象,可以用于访问当前对象的属性和方法。当一个类中存在多个同名的变量或方法时,用 this 关键字可以明确指定是哪个。同时,this 还可以用于实现链式调用(method chaining)的功能。

示例代码:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 使用 this 访问当前对象的属性
    public void introduce() {
        System.out.println("My name is " + this.name + ", and I am " + this.age + " years old.");
    }

    // 使用 this 实现链式调用
    public Person setName(String name) {
        this.name = name;
        return this;
    }

    public Person setAge(int age) {
        this.age = age;
        return this;
    }
}

// 测试代码
Person person = new Person("Tom", 18);
person.introduce(); // 输出:"My name is Tom, and I am 18 years old."

person.setName("Jerry").setAge(20); // 链式调用

 

super

super 关键字主要用于表示父类对象,可以用于访问父类的属性和方法。当子类和父类中存在同名的变量或方法时,用 super 关键字可以明确指定是父类的属性或方法。同时,super 还可以用于调用父类的构造方法。

示例代码:

public class Person {
    protected String name;

    public Person(String name) {
        this.name = name;
    }

    // 父类的普通方法
    public void introduce() {
        System.out.println("My name is " + this.name);
    }
}

public class Student extends Person {
    private int grade;

    public Student(String name, int grade) {
        // 调用父类的构造方法
        super(name);
        this.grade = grade;
    }

    // 子类重写的方法
    public void introduce() {
        super.introduce(); // 调用父类的普通方法
        System.out.println("I am a student in grade " + this.grade);
    }

    // 使用 super 访问父类的属性
    public void printName() {
        System.out.println(super.name);
    }
}

// 测试代码
Person person = new Person("Tom");
person.introduce(); // 输出:"My name is Tom"

Student student = new Student("Jerry", 3);
student.introduce(); // 输出:"My name is Jerry \n I am a student in grade 3"

student.printName(); // 输出:"Tom"

this 和 super 的区别主要在于它们表示的对象不同,this 表示当前对象,而 super 表示父类对象。此外,this 主要用于访问当前对象的属性和方法,或者实现链式调用;super 主要用于访问父类的属性和方法,或者调用父类的构造方法。

Guess you like

Origin blog.csdn.net/weixin_58724261/article/details/131216574