用this调用构造函数

来源:互联网 发布:windows自动修复 编辑:程序博客网 时间:2024/06/15 23:49
public class H{       int petalCount=0;    String s;    H(String ss)    {        s=ss;        print(s);    }    H(int petals)    {        petalCount=petals;        print(petalCount);    }    H(String s,int petals)    {        this(s);//用this调用该类的构造函数        petalCount=petals;    }    public static void main(String[] args)    {        H flower1=new H(4);//4        H flowre2=new H("hello");        H flower3=new H("nihao",6);        print(flower3.petalCount);    }                  }    

输出:
4
hello
nihao
6

public class H{       int petalCount=0;    String s;    H(String ss)    {        s=ss;        print(s);    }    H(int petals)    {        petalCount=petals;        print(petalCount);    }    H(String s,int petals)    {        this(s);        this(petals);    }    public static void main(String[] args)    {        H flower1=new H(4);        H flowre2=new H("hello");        H flower3=new H("nihao",6);//报错 因为只能在构造函数中使用一次this调用其他构造函数    }                  }                  

报错

public class H{       int petalCount=0;    String s;    H(String ss)    {        s=ss;        print(s);    }    H(int petals)    {        petalCount=petals;        print(petalCount);    }    H(String ss,int petals)    {        this(petals);        s=ss;    }    public static void main(String[] args)    {        H flower1=new H(4);        H flowre2=new H("hello");        H flower3=new H("nihao",6);        print(flower3.s);    }                  }                  

输出:
4
hello
6
nihao

知识点:
在构造函数中可以调用该类的其他构造函数,且在一个构造函中只能调用一次该类的其他构造函数,且这句调用语句必须写在本函数的第一行。

注意:不能在类的其他方法中使用this调用该类的构造函数。

public class H{       String s;    H(String ss)    {        s=ss;        print(s);    }    void prints()    {        this("123");      }    public static void main(String[] args)    {        H a=new H("bilibili");        a.prints(); //报错,不能在类的其他方法中用this使用该类的狗仔函数    }                  } 
package net.mindview;import static net.mindview.util.Print.*;// 要求类中有两个构造函数,且在第一个构造函数中用this调用第二个构造函数public class H{       int a;    String str;    H(int a1,String str1)    {        this(a1);        str=str1;    }    H(int a1)    {        a=a1;    }    public static void main(String[] args)    {        H haha=new H(1,"hello world!");        print(haha.a);        print(haha.str);    }                  }   

输出:
1
hello world!

原创粉丝点击