Java在构造函数中调用其它构造函数


在Java中在构造函数中调用其它构造函数的方式与C++不同,需要使用this关键字,而不是像C++直接使用构造函数名来调用。

public class Good {
    private String gName;
    private double gPrice;
    private int gCategory;
    private String gCategoryName;

    public static void main(String[] args) {
        Good good = new Good("华为P30",3895.5,"手机");
        System.out.println(good);
    }

    public Good(String gName, double gPrice, int gCategory) {
        this(gName,gPrice,gCategory,"");
    }
    public Good(String gName, double gPrice, String gCategoryName) {
        this(gName,gPrice,555,gCategoryName);
    }
    public Good(String gName, double gPrice, int gCategory, String gCategoryName) {
        this.gName = gName;
        this.gPrice = gPrice;
        this.gCategory = gCategory;
        this.gCategoryName = gCategoryName;
    }
    @Override
    public String toString() {
        return "Good{" +
                "gName='" + gName + '\'' +
                ", gPrice=" + gPrice +
                ", gCategory=" + gCategory +
                ", gCategoryName='" + gCategoryName + '\'' +
                '}';
    }
}

运行结果为:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM