Java中的this和super关键字的作用

this 和 super 是 Java 中两个重要的关键字,用于引用类的当前对象和父类对象。

1.this 关键字

  • this 引用当前对象的实例。在类的方法中,可以使用 this 来引用当前对象。
  • 通过 this 访问类中的成员变量和成员方法。例如 this.count 访问变量,this.print() 调用方法。
  • 在构造方法中使用 this 调用其他构造方法。
  • this 不能在类的静态方法中使用。

在成员方法中使用this:

public class Person {

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

  public void printName() {
    System.out.println(this.name);
  }
}

通过this访问成员变量name和成员方法printName()。

构造方法中使用this调用其他构造方法:

public class Person {

  String name;
  int age;

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

this调用同一个类的其他构造方法。

2.super 关键字

  • super 引用父类对象。在子类中可以使用 super 来引用父类。
  • 通过 super 访问父类中的成员变量和成员方法。例如 super.count 访问变量,super.print() 调用方法。
  • 在子类构造方法中使用 super() 调用父类构造方法。
  • super 必须在子类方法和构造方法中使用,不能在静态方法中使用。

子类构造方法中使用super调用父类构造方法:

public class Student extends Person {

  String school;

  public Student(String name, String school) {
    super(name);
    this.school = school;
  }
}

super调用父类Person的构造方法。

子类中使用super访问父类成员:

public class Student extends Person {

  public void print() {
    super.printName(); //调用父类方法
    System.out.println(super.name); //访问父类变量
  }

}

super访问父类Person的成员。 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个帅气的程序员ovo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值