注册 登录
编程论坛 JAVA论坛

java的一个小问题,高手过来指点......

新人学习 发布于 2018-10-03 10:23, 2270 次点击
//Calling constructors with "this"               用“this”调用构造函数

public class Flower
{
    int petalCount = 0;
    String s = "initial value";
    Flower(int prtals)
    {
        petalCount = prtals;
        System.out.println("Constructor w/ String arg only, prtalcount = " + petalCount);
    }
   
    Flower(String ss)
    {
        System.out.println("Constructor w/ String arg only, s = " + ss);
        s = ss;
    }
   
    Flower(String s, int petals)
    {
        this(petals);                    //这个语句什么意思?是怎么执行的?
        //!  this(s);  //Can't call two!      //不能叫两个!
        this.s = s;  //Another use of "this"         // “this”的另一个用法
        System.out.println("String & int args");          //字符串和字符串
    }
   
    Flower()
    {
        this("hi", 47);
        System.out.println("default constructor (no args)");               //缺省构造函数(无ARG)
    }
   
    void printPetalCount()
    {
        //! this(11);     //Not inside non - constructor!           不在非构造函数之内!
        System.out.println("petalCount = " + petalCount + " s = " + s);
    }
   
    public static void main(String[] args)
    {
        Flower x = new Flower();
        x.printPetalCount();
    }
}
3 回复
#2
林月儿2018-10-03 22:28
调用上面重载的构造器啊
Flower(int prtals)这个方法

[此贴子已经被作者于2018-10-3 23:22编辑过]

#3
红柚2018-10-04 19:01
Flower(String s, int petals){  //参数列表里petals是int类型
        this(petals);   //此时相当于参数是一个int,所以重载的就是Flower(int prtals){ ... }这个方法
}
找的时候只要看方法名和参数列表是否有对应就很简单了,重载构造器的名字是类名,目前我学到的是这样
#4
疯狂的小a2018-10-04 19:47
只有本站会员才能查看附件,请 登录

this指当前对象,可以理解为Class类,调用有参构造函数
1