this与super
this
1.this能出现在实例方法和构造方法中。
2.this的语法是:this.
、this()
。
this.属性名 [访问本类中的属性]
this.方法名(实参) [访问本类中的方法]
this(实参) [调用本类的其它构造方法]
3.this不能使用在static静态方法中。
4.this. 大部分情况下是可以省略的。
5.this. 在区分局部变量和实例变量的时候不能省略。
public void setName(String name){
this.name = name;
}
6.this() 只能出现在构造方法第一行,通过当前的构造方法去调用本类
中其它的构造方法。目的:代码复用
super
1.super能出现在实例方法和构造方法中。
2.super的语法是:super.
、super()
。
super.属性名 [访问父类中的属性]
super.方法名(实参) [访问父类的方法]
super(实参) [调用父类的构造方法]
3.super不能使用在static静态方法中。
4.super. 大部分情况下是可以省略的。
5.super. 在子类和父类有同名属性或方法时,通过子类想调用父类属性或方法时不能省略。
6.super() 只能出现在构造方法第一行,通过当前的构造方法去调用父类
中其它的构造方法。目的:创建子类对象的时候,先初始父类型的特征。
7.当一个构造方法第一行,既没有this()
又没有super()
的话,默认会有一个super()
。
8.super(实参) 的作用是:初始化当前对象的父类型特征。
9.super 不是引用,不保存内存地址,不指向任何对象,只代表当前对象内部的那一块父类型的特征。
//实例方法
public void doSome(){
//输出:类名@地址
System.out.println(this);
//输出"引用"的时候,会自动调用引用的toString()方法
//System.out.println(this.toString());
//编译错误:需要'.'
//System.out.println(super);
}
this()与super()代码示例
public class SuperTest01{
public static void main(String[] args){
new C(); //123654
}
}
class A{
//A的无参构造方法
public A(){
//默认super(); 调用Object的无参构造方法
System.out.println("A的无参构造执行"); //1
}
}
class B extends A{
//B的无参构造方法
public B(){
//默认super();
System.out.println("B的无参构造执行"); //2
}
//B的有参构造方法
public B(String name){
this();
System.out.println("B的有参构造执行"); //3
}
}
class C extends B{
//C的无参构造方法
public C(){
this("lisi");
System.out.println("C的无参构造执行"); //4
}
//C的有参构造方法
public C(String name){
this(name,18);
System.out.println("C的有参构造执行(String name)"); //5
}
//C的有参构造方法
public C(String name, int age){
super(name);
System.out.println("C的有参构造执行(String name, int age)"); //6
}
}
结果:
A的无参构造执行
B的无参构造执行
B的有参构造执行
C的有参构造执行(String name, int age)
C的有参构造执行(String name)
C的无参构造执行