首先,this
代表自身对象的引用,是一个地址。super是一个关键字,不能将super
赋给另一个对象变量,它只是一个指示编译器调用超类方法的特殊关键字。
this作用
- 引用隐式参数。
- 调用该类其他的构造器,此时必须这条语句必须是第一条语句。当类没有提供任何构造器的时候,系统才会提供一个默认的构造器。这个构造器将实例域设置为默认值。如果类中提供了至少一个构造器,系统不会提供默认的构造器。
class A{
public A(){
System.out.println("father class!");
}
}
class B extends A{
private String s;
public B(){
System.out.println("sub class not parameters");
}
public B(String s){
this(); //调用无参数的B类构造器,必须放在第一条语句。
this.s=s;//形参与成员名字重名,用this来区分,this表示隐式参数
System.out.println("sub class with String parameters "+s);
}
}
public class Outer {
public static void main(String args[]){
B b=new B("Hello world!");
}
}
super关键字
- 调用超类的方法。
- 调用超类的构造器。如果子类的构造器没有显式地调用超类的构造器,则将自动地调用超类默认(没有参数)的构造器
- 调用超类构造器的语句只能作为另一个构造器的第一条语句出现。
this()
和super()
不能同时出现在一个构造函数里面。this()
和super()
都不能在static
环境中使用,包括static
变量,static
方法,static
块。
class A{
public A(){
System.out.println("father class!");
}
void display(){
System.out.println("display of father class!");
}
}
class B extends A{
private String s;
public B(){
System.out.println("sub class not parameters");
}
public B(String s){
super(); //调用父类A的构造器,必须是子类构造器的第一条语句。
super.display(); //调用父类的display方法
display(); //本类的display()
System.out.println("sub class with String parameters "+s);
}
void display(){ //重写的display
System.out.println("display of sub class!");
}
}
public class Outer {
public static void main(String args[]){
B b=new B("Hello world!");
}
}
输出结果:
father class!
display of father class!
display of sub class!
sub class with String parameters Hello world!
如有错误,欢迎留言指正!