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

this关键字的作用:
1.调用自己的其他构造方法(需将this放在第一行)
2.代表指向本对象的引用
3.访问本对象的属性或方法

this表示当前对象引用(并不是当前对象),可以借助this来访问对象的字段和方法。

class Person{
    private String name;
    private int age;
    private String sex;

    public Person(){
        this("bit",12,"man");
        //this必须放在无参构造方法的第一行
    }

//    public Person(){
//        this("bit",12);
//    }

    public Person(String name,int age,String sex){
        this.name = name;  //该变量是类的成员变量
        this.age = age;
        this.sex = sex;
    }

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

    public void show(){
        System.out.println("name: "+name+" age: "+age+" sex: "+sex);
    }
}

public class thisDemo {
    public static void main(String[] args) {
        Person person = new Person();
        person.show();
    }
}

在构造函数的内部可以使用this关键字,构造函数是用来构造对象的,对象还没有构造好就是用了this,此时this代表的还是当前对象的引用。

super关键字的作用:
1.调用父类的构造方法
2.去访问被隐藏的父类的属性
3.去调用被覆写的父类的方法

super表示获取到父类实例的引用

  1. 使用了super 来调用父类的构造器
public Bird(String name) { 
     super(name);
}
  1. 使用 super 来调用父类的普通方法
class Animal0{
    protected String name;

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

    public void eat(String food){
        System.out.println("小动物");
        System.out.println(this.name + "正在吃" + food);
    }

    public  void eatingFish(){
        System.out.println(this.name + "爱吃鱼");
    }
}

public class Cat extends Animal0{

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

    public void eat(String food){
        System.out.println("我是猫");
        System.out.println(this.name + "正在吃" + food);
        super.eatingFish();
    }

    public static void main(String[] args) {
        Animal0 animal0 = new Cat("喵");
        animal0.eat("大肥鱼");
    }
}

super和this的区别

thissuper
访问本类中的属性和方法由子类访问父类中的属性和方法
先查找本类,如果本类没有就调用父类不查找本类而直接调用父类
表示当前对象
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值