this和super的区别

一、this

this是自身的一个对象,代表对象本身,可以理解为:指向对象本身的一个引用。
this的用法在java中大体可以分为3种:

1、普通的直接引用

this相当于是指向当前对象本身。   
2、形参与成员名字重名,用this来区分:

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

3.调用本类的其他构造方法
依赖形参和实参的关系

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

二、super

super可以理解为是指向自己父类对象的一个引用,而这个父类指的是离自己最近的一个父类   
super也有三种用法:

1、普通的直接引用与this类似,super相当于是指向当前对象的父类对象部分的引用,这样就可以用super.xxx来引用父类的成员。
2、子类中的属性行为或方法与父类中的属性行为或方法同名时,用super进行区分
当子类重写父类型为 super.调用父类实现 this.调用子类实现

class Person{
    protected String name;
 
    public Person(String name) {
        this.name = name;
    }
 
}
 
class Student extends Person{
    private String name;
 
    public Student(String name, String name1) {
        super(name);
        this.name = name1;
    }
 
    public void getInfo(){
        System.out.println(this.name);      //Child
        System.out.println(super.name);     //Father
    }
 
}
public class Test {
 
    public static void main(String[] args) {
       Student s1 = new Student("Father","Child");
       s1.getInfo();
 
    }
 
}

三、引用父类构造函数

super(参数):调用父类中的某一个构造函数(应该为构造函数中的第一条语句)。
this(参数):调用本类中另一种形式的构造函数(应该为构造函数中的第一条语句)。

四、super和this的异同:

super:它引用父类中的成员
super.成员函数据名(实参)

this:它代表当前对象名
super()和this()类似,区别是,super()在子类中调用父类的构造方法,this()在本类内调用本类的其它构造方法。

super()和this()均需放在构造方法内第一行。 尽管可以用this调用一个构造器,但却不能调用两个。
this和super不能同时出现在一个构造函数里面,因为this必然会调用其它的构造函数,其它的构造函数必然也会有super语句的存在,所以在同一个构造函数里面有相同的语句,就失去了语句的意义,编译器也不会通过。
this()和super()都指的是调用构造方法,所以,均不可以在static环境中使用。包括:static变量,static方法,static语句块。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值