super和this的使用和作用

super和this的含义
super :代表父类的存储空间标识(可以理解为父亲的引用)。
this :代表当前对象的引用(谁调用就代表谁)。
super和this的用法

  1. 访问成员

this.成员变量
super.成员变量
‐‐
‐‐
本类的
父类的
this.成员方法名()
super.成员方法名()
‐‐
本类的
父类的
‐‐
用法演示,代码如下:

class  Animal  {
public  void  eat() {
System.out.println("animal  :  eat");
}
}
class  Cat  extends Animal  {
public  void  eat() {
System.out.println("cat  :  eat");
}
public  void  eatTest() {
this.eat();
super.eat();
//  this
调用本类的方法
//  super  调用父类的方法
}
}
public  class  ExtendsDemo08 {
public  static  void main(String[]  args)  {
Animal  a  = new  Animal();
a.eat();
Cat  c  = new  Cat();
c.eatTest();
}
}
输出结果为:
animal  :  eat
cat  :  eat
animal  :  eat
  1. 访问构造方法
    this(…)
    ‐‐
    ‐‐
    本类的构造方法
    父类的构造方法
    super(…)
    子类的每个构造方法中均有默认的super(),调用父类的空参构造。手动调用父类构造会覆盖默认的super()。
    super() 和 this() 都必须是在构造方法的第一行,所以不能同时出现。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值