21xrx.com
2024-09-20 05:41:53 Friday
登录
文章检索 我的文章 写文章
Java编写商品类型代码
2023-06-19 05:09:58 深夜i     --     --
Java编程 商品类型 类定义

在Java编程中,经常需要定义一个商品类型来表示不同种类的商品。下面是一个示例代码,用来定义商品类型,并为之添加属性和方法。

首先,我们定义一个Product类,包含以下属性:

名称(name):字符串类型;

价格(price):双精度类型;

库存(stock):整型;

描述(description):字符串类型;

然后,我们为Product类添加以下方法:

getName():获取商品的名称;

getPrice():获取商品的价格;

getStock():获取商品的库存;

getDescription():获取商品的描述;

setPrice(price):设置商品的价格;

setStock(stock):设置商品的库存;

下面是Java代码:

public class Product {

  private String name;

  private double price;

  private int stock;

  private String description;

  public Product(String name, double price, int stock, String description)

    this.name = name;

    this.price = price;

    this.stock = stock;

    this.description = description;

  public String getName()

    return name;

  public double getPrice()

    return price;

  public int getStock()

    return stock;

  public String getDescription()

    return description;

  public void setPrice(double price)

    this.price = price;

  public void setStock(int stock)

    this.stock = stock;

}

通过这个Product类,我们可以创建不同的商品对象,并获取它们的属性或执行它们的方法。例如,我们可以创建一个Book类,继承自Product类,并添加一个作者(author)的属性和一个获取作者(getAuthor)的方法:

public class Book extends Product {

  private String author;

  public Book(String name, double price, int stock, String description, String author) {

    super(name, price, stock, description);

    this.author = author;

  }

  public String getAuthor()

    return author;

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章