Java中this和super的使用!!!

本文记录下在Java中, this 和 super 是两个关键字,作用是用于引用当前对象和父类对象。

1. this

this 关键字用于引用当前对象,主要有以下用途:

  • 当方法的参数名和实例变量名相同时,可以使用 this 关键字来区分
  • 在构造方法中调用其他构造方法:通过 this() 来调用同一个类中的其他构造方法。
  • 返回当前对象:在方法中返回当前对象的引用。

2. super 关键字:

  • super 关键字用于引用父类对象,可以在子类中使用。
  • 主要用有:
    • 调用父类构造方法,通过 super() 来调用父类的构造方法。
    • 访问父类的成员变量和方法,可以使用 super 关键字来访问父类的成员变量和方法。
    • 在子类中重写父类方法时,使用 super 来调用父类的方法

Java示例代码:

class Parent {
    String name;

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

    public void display() {
        System.out.println("Parent Name: " + this.name);
    }
}

class Child extends Parent {
    int age;

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

    public void display() {
        super.display(); // 调用父类方法
        System.out.println("Child Age: " + this.age);
    }
}

public class Main {
    public static void main(String[] args) {
        Child child = new Child("Alice", 10);
        child.display();
    }
}



总结

   this 关键字用于引用当前对象的成员变量, super 关键字用于调用父类的构造方法和方法。通过 this 和 super 关键字,可以方便地访问当前对象和父类对象的成员。
  希望对看到本文的你有帮助。



上一篇 java面向对象三大特征
记得点赞收藏哦!!!
下一篇 Java静态代理和动态代理详解
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值