super 和 this 的异同

本文详细介绍了Java中的`super`和`this`关键字的区别和使用场景,通过代码示例展示了它们如何调用父类和本类的构造方法、属性及方法。了解这些概念对于深入理解面向对象编程至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

赶时间的看总结就好了。

异同

super

  • super();调用父类构造方法;
  • super.date; 调用父类的属性;
  • super.func(); 调用父类的方法。

this

  • this();调用构造方法
  • this.date; 调用本类属性;
  • this.func(); 调用本类方法。

代码示例

super

public class TestSuperAndThis extends Person{
    public int length;
    public String name;

    public TestSuperAndThis(int length, String name) {
        super(name);
        this.length = length;
        this.name = name;
    }

    public void function() {
        super.method();
        System.out.println(super.name);
    }
    
    public static void main(String[] args) {
        TestSuperAndThis test = new TestSuperAndThis(18,"逍遥");
        test.function();
    }
}

class Person {

    /**
     * 3. 调用父类的属性
     */
    public String name;

    /**
     * 1. 调用父类构造方法
     * @param name
     */
    public Person(String name) {
        System.out.println(name + "调用了父类的构造方法");
    }

    /**
     * 2. 调用父类的普通方法
     */
    public void method() {
        System.out.println("调用父类的普通方法");
    }
}
逍遥调用了父类的构造方法
调用父类的普通方法
null

this

public class TestSuperAndThis {
    public int length;
    public String name;

    /**
     * 1. 调用本类的构造方法
     * @param name
     */
    public  TestSuperAndThis(String name) {
        this();
    }

    public TestSuperAndThis() {
        System.out.println("调用本类的其他构造方法");
    }


    /**
     * 2. 调用本类的普通方法
     */
    public void function() {
        this.method();
    }

    /**
     * 3. 调用本类的属性
     */
    public void method() {
        System.out.println("调用本类的普通方法");
        String newName = this.name;
        System.out.println(newName);
    }
    public static void main(String[] args) {
        TestSuperAndThis test = new TestSuperAndThis("逍遥");
        test.function();
    }
}
调用本类的其他构造方法
调用本类的普通方法
null
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值