super和this的异同:
1)super(参数):调用父类的构造方法。
2)this(参数):调用本类的其他构造方法。
3)都必须放在构造方法的第一行。
4)super:引用父类中的成员,当子类和父类中的方法重名时,这样用。
5)this:代表当前对象名(在程序中易产生二义性之处,应使用this来指明当前对象;如果函数的形参与类中的成员 数据同名,这时需用this来指明成员变量名)。
6)this()和super()都指的是对象,所以,均不能在static环境中使用。包括:static变量,static方法,static语句块。
7)从本质上讲,this是一个指向本对象的指针, 然而super是一个Java关键字。
class Creature extends Object{
//Creature会去调用父类Object的默认的无参构造方法
publicCreature() {
System.out.println("Creature无参数的构造器");
}
}
class Animal extends Creature {
publicAnimal(String name) {
//不管这里有不有super它都会去执行父类的无参构造方法
//super();
System.out.println("Animal带一个参数的构造器,该动物的name为" + name);
}
publicAnimal(String name, int age) {
//使用this调用同一个重载的构造器
this(name);
System.out.println("Animal带2个参数的构造器,其age为" +age);
}
}
public class Wolf extends Animal {
publicWolf() {
//显式调用父类有2个参数的构造器
super("土狼", 3);
System.out.println("Wolf无参数的构造器");
}
publicstatic void main(String[] args) {
Wolfwolf = new Wolf();
}
}