java——用this调用构造方法:

2019年2月16日23:56:49 发表评论 1,118 views
/**
 * Created by xabcd on 2019/2/16.
 */
class thistook

{
    String name;
    int age;
    public thistook()
    {
        System.out.println("1.public thistook()");
    }
    public thistook(String name,int age)
    {
        //调用本类中无参构造方法:
        this();
        this.name = name;
        this.age = age;
        System.out.println("2.public thistook()(String name,int age");
    }

}


/**
 * Created by xabcd on 2019/2/16.
 */
public class thistook2
{
    public static void main(String args[])
    {
        new thistook("张三",25);
    }
}





1.public thistook()
2.public thistook()(String name,int age

有的 读者 经常 会有 这样 的 疑问: 如果 我把 this() 调用 无 参 构造 方法 的 位置 任意 调换, 那不 就可 以在 任何时候 都可以 调用 构造 方法 了 么? 实际上 这样 理解 是 错误 的。 构造 方法 是在 实例 化 一个 对象 时 被 自动 调用 的, 也就是说 在 类 中的 所有 方法 里, 只有 构造 方法 是 被 优先 调用 的, 所以 使用 this 调用 构造 方法 必须 也 只能 放在 类 中。

 

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: