java this关键字和super关键字有什么区别

this和super的区别

this

this是当前对象的引用,指向了这个类类的对象。作用:

1.可以调用类中成员的属性。

方式:class student{
    private int age;
    private String name;
}
 //含参的构造方法
 public student (int age ,String name){
     this.age=age;
     this.name=name;
 }

//当传入参数的名字与成员属性的名字相同时,this有效的防止参数自己给自己赋值。

2.可以调用类中的方法

class student{
    private int age;
    private String name;
    public student(int age,String name){
        this.age=age;
        this.name=name;
    }
    public void eat(){
        System.out.println(this.name+"在吃饭");
    }
    public void show(){
        this.eat();
    }
}

3.调用自身构造方法

:必须放在第一行,且只能调用一个构造方法,且只能在构造方法中通过this调用构造方法,不能再普通方法中。
this是一个引用: 在这个构造方法中,使用了this关键字,此时对象还没有构造好,this代表当前对象的引用。

class student{
    private int age;
    private String name;
    public student(){
        this(15,"zhangsan");
    }
    //这两个构造方法的关系为重载
    public student(int age,String name){
        this.age=age;
        this.name=name;
    }
}

super

super代表所继承的父类的引用。用法:

1.使用super来调用父类的构造方法

public Bird(String name) {
super(name);
}

2.使用super来调用父类的普通方法

public class Bird extends Animal {
public Bird(String name) {
super(name);
}
@Override
public void eat(String food) {
super.eat(food);
System.out.println("我是一只小鸟");
System.out.println(this.name + "正在吃" + food);
}
}

总结:

this访问的是本类的属性和方法,super访问的是父类的属性和方法;
访问时this会先查找本类,如果本类没有,才会去访问父类,而super直接访问调用父类;
this代表当前对象的引用,super不能;
this调用本类构造方法,必须放在本类构造方法的第一行,super调用父类构造方法,放在字类的构造方法首行。
在对拥有父类的子类进行初始化时,父类的构造方法也会执行,且优先于子类的构造函数执行;因为每一个子类的构造函数中的第一行都有一条默认的隐式语句super()
this(参数)和super(参数)不能同时出现在构造方法当中
this和super不能用于static修饰的变量,方法,代码块;因为this和super都是指的是对象(实例),而static和对象无关。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值