构造方法的定义、重载、调用、使用

(1)定义商品类Goods,
成员变量有:商品名称(name),单价(price),库存量(inventories)。
*对这3个属性进行封装。
方法有:
① show(),用于输出商品的成员变量值,每个成员变量值之间用空格分隔。
② 定义无参的构造方法。
③ 定义带2个参数的构造方法,参数分别表示商品名称、单价属性的值。
④ 定义带3个参数的构造方法,参数分别表示商品名称、单价、库存量的值 。
(2)定义测试类GoodsDemo,包含主方法。
创建并使用Goods类的对象,给对象的属性赋值,通过show()方法输出属性值。
主方法功能要求如下:
① 调用无参构造方法,创建对象1,输出对象,再通过调用setXXXX方法给对象赋值,输出对象1。
② 调用带2个参数的构造方法,创建对象2,输出对象2。
③ 调用带3个参数的构造方法,创建对象3,输出对象3。

public class Goods{
    private String name ;
    private int inventories ;
    private double price;
    public Goods ( String name ){
        this.name = name ;
    }
    public String getName(){
        return this . name ;
    }
    public int getInventories(){
        return this . inventories ;
    }
	public void setName (String name ){
        this.name = name ;
    }
	public double getPrice( ){
        return this.price;
    }
	public void setPrice (double price ){
        this.price = price ;
    }
	public void setInventories(int inventories ){
        this. inventories = inventories ;
    }
    Goods(){}
    Goods(String name1,double price1) {
        name = name1;
        price = price1;
    }
    Goods(String name2 ,double price2,int inventories2){
        name = name2;
        price = price2;
        inventories = inventories2;
    }
    public void show(){
        System.out.println("商品名称: " + name + "       商品单价:" + price + "       库存量: " + inventories);
    }
}
class PersonTest{
    public static void main (String args[] ) {
        Goods p1=new Goods();
        p1. setName( "藏獒" );
        p1. setInventories(20);
        p1. setPrice(9287.00);
        p1. show();
        Goods p2=new Goods( "藏布拉多寻回犬", 2254.00);
        p2. setInventories(22);
        p2. show();
        Goods p3=new Goods("哈士奇",3566.00,3);
        p3. show();
    }
}`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

量子代码时空

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值