Java中this和super的区别

2023-11-15面试1 分钟113 次阅读
AI 摘要鱼粮不足,AI 今天先歇着 · 正文在下面

this

this表示当前对象,具体有以下特性:

this.属性:区别成员变量和局部变量;
this.xxx():调用本类的某个方法;
this():表示调用本类构造方法,只能用在构造方法的第一行语句;
this关键字只能出现在非static修饰的代码中。

super

super表示当前类的父类对象,具体有以下特性:

super.属性:表示父类对象中的成员变量;
super.xxx():表示父类对象中定义的方法;
super():表示调用父类构造方法,可以指定参数,比如super("Salmon",24),任何一个构造方法的第一行默认是super(),它可以写上,如果未写,会隐式调用该方法,该方法只能在构造方法的第一行使用;
this()和super()都只能在构造的第一行出现,所以只能选择其一。写了this()就不会隐式调用super();

例子

这里我定义一个动物类

java 复制代码
package t1;

/**
 * 动物类
 *
 * @author Salmon
 * @since 2023-11-15
 */
public class Animal {
    
    public String name;

    public Animal() {
    }

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

    public void sleep() {
        System.out.println("Animal sleep");
    }

    public void eat() {
        System.out.println("Animal eat");
    }

}

定义一个猫类

java 复制代码
package t1;

/**
 * 猫类
 *
 * @author Salmon
 * @since 2023-11-15
 */
public class Cat extends Animal {

    public String color;

    public Cat() {
    }

    public Cat(String name, String color) {
        super(name);
        this.color = color;
    }

    @Override
    public void sleep() {
        System.out.println(this.color + " cat " + this.name + " sleep");
    }

    @Override
    public void eat() {
        System.out.println(this.color + " cat " + this.name + " eat");
    }
}

可以看到我这里Cat类没有使用this方法给从父类继承的熟悉name赋值的,而是调用了父类的有参构造方法,我们试着测试打印下

java 复制代码
package t1;

/**
 * @author Salmon
 * @since 2023-11-15
 */
public class Test {

    public static void main(String[] args) {
        Cat cat = new Cat("lucy","white");
        cat.sleep();
        cat.eat();
    }

}
image.png

结论

综上,它们两者主要有以下区别:
不同点:

  1. super()主要是对父类构造函数的调用,this()是对重载构造函数的调用
  2. super()主要是在继承了父类的子类的构造函数中使用,是在不同类中的使用;this()主要是在同一类的不同构造函数中的使用

相同点:
super()和this()都必须在构造函数的第一行进行调用,否则就是错误的

觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句