在学习过程中,经常遇到super()与this()这两个方法。关于这两者的区别,根据我的理解,现总结归纳一下:
Over the process of learning Java SE,I have frequently encoutered the question that how to use the method of super & this.As with the differences between the both,I make a summary now based on my understanding.For the sake of strenthening my memory I write down these words.
区别:super是指基类对象;而this是指当前对象
举例:super() //调用基类默认的构造方法
super(XXX) //调用以XXX为形参的构造方法
super.method() //调用基类中的方法
super.variable //返回基类的成员变量
this.method() //表示当前对象的方法
this.variable() //表示当前对象的成员变量
使用super&this应该注意些什么?
1)调用super()必须写在子类构造方法的第一行,否则编译不通过。每个子类构造方法的第一条语句,都是隐含地调用super(),如果父类没有这种形式的构造函数,那么在编译的时候就会报错。
2)super()和this()类似,区别是,super从子类中调用父类的构造方法,this()在同一类内调用其它方法。
3)super()和this()均需放在构造方法内第一行。
4)尽管可以用this调用一个构造器,但却不能调用两个。
5)this和super不能同时出现在一个构造函数里面,因为this必然会调用其它的构造函数,其它的构造函数必然也会有super语句的存在,所以在同一个构造函数里面有相同的语句,就失去了语句的意义,编译器也不会通过。
6)this()和super()都指的是对象,所以,均不可以在static环境中使用。包括:static变量,static方法,static语句块。