任务三:this()的用法
package Test;
public class Animal {
static String type;
static String eat;
static int foots;
public Animal() {
type="Tiger";
eat="meat";
foots=4;
System.out.println(type + " usually have " + foots + " legs,eat " + eat );
}
public Animal(int a){
this();
type="Tiger";
eat="meat";
foots=a;
System.out.println(type + " usually have " + foots + " legs,eat " + eat );
}
public Animal(int a,String b){
this(a);
type="Tiger";
eat=b;
foots=a;
System.out.println(type + " usually have " + foots + " legs,eat " + eat );
}
public Animal(int a,String b,String c){
this(a,b);
type=c;
eat=b;
foots=a;
System.out.println(type + " usually have " + foots + " legs,eat " + eat );
}
{
type="Tiger";
eat="meat";
foots=4;
System.out.println("Initialization block was finished !");
}
public static void main(String[] args) {
new Animal(2,"meat and vegetables","Human");
}
}
首先还是先看我们的 main() 方法:
public static void main(String[] args) {
new Animal(2,"meat and vegetables","Human");
}
这里就是一个简单的实例化,传过去三个参数,类型分别为 int , String , String,那么此时,Java就会寻找有三个参数的 Animal(int ,String ,String ) ,
public Animal(int a,String b,String c){
this(a,b);
type=c;
eat=b;
foots=a;
System.out.println(type + " usually have " + foots + " legs,eat " + eat );
}
非常遗憾的是这个构造器中有一个 this(a,b),那就不得不先去调用拥有两个参数的 Animal(int ,String ) 了,
public Animal(int a,String b){
this(a);
type="Tiger";
eat=b;
foots=a;
System.out.println(type + " usually have " + foots + " legs,eat " + eat );
}
很可惜,这里也有 this(a) ,而它指向的 Animal(int) 里又有 this() ,那我们就直接跳到 this() 指向的 Animal() 吧,到了这里,又要再上一级,先到类里去,看看类里有没有可执行语句,于是就会检测到下列代码:
static String type;
static String eat;
static int foots;
找到这个之后并不会马上执行 Animal() 而是先找初始化块
{
type="Tiger";
eat="meat";
foots=4;
System.out.println("Initialization block was finished !");
}
这里会输出 Initialization block was finished ! 说明初始化块完成,接下来依次进入 Animal() ,Animal(int) ,Animal(int,String) ,Animal(int,String,String) ,中执行
在 Animal() 中,都还是默认值,输出 Tiger usually have 4 legs,eat meat
public Animal() {
type="Tiger";
eat="meat";
foots=4;
System.out.println(type + " usually have " + foots + " legs,eat " + eat );
}
在 Animal(int) 中,脚数变更为了传递过来的 2,输出 Tiger usually have 2 legs,eat meat
public Animal(int a){
this();
type="Tiger";
eat="meat";
foots=a;
System.out.println(type + " usually have " + foots + " legs,eat " + eat );
}
在 Animal(int,String) 中,种类变更为了传递过来的 Human ,输出 Human usually have 2 legs,eat meat
public Animal(int a,String b){
this(a);
type="Tiger";
eat=b;
foots=a;
System.out.println(type + " usually have " + foots + " legs,eat " + eat );
}
在 Animal(int,String,String) 中,食物变更为了传递过来的 meat and vegetables ,输出 Human usually have 2 legs,eat meat and vegetables
public Animal(int a,String b,String c){
this(a,b);
type=c;
eat=b;
foots=a;
System.out.println(type + " usually have " + foots + " legs,eat " + eat );
}