【发布时间】:2017-04-13 05:23:45
【问题描述】:
public class TVSet {
private String brand;
private double price;
public TVSet()
{
brand = "";
price = 0.0;
}
public String getbrand()
{
return this.brand;
}
public double getprice()
{
return this.price;
}
public void setbrand(String brand)
{
if(brand!=null)
{
this.brand = brand;
}
else
{
System.out.println("INVAILD VALUE");
}
}
public void setprice(double price)
{
if(price>=0)
{
this.price = price;
}
else
{
System.out.println("INVALID VALUE");
}
}
public void TVSet(String brand, double price)
{
if(brand!=null)
{
this.brand= brand;
}
else
{
System.out.println("INVALID VALUE");
}
if(price>=0.0)
{
this.price = price;
}
else
{
System.out.println("INVALID VALUE");
}
}
@Override
public String toString()
{
//double temp = this.getprice();
//DecimalFormat f = new DecimalFormat("##,00");
//String price2 = f.format(temp);
return String.format("%s, %.2f", brand, price);
}
@Override
public boolean equals(Object o)
{
if(o instanceof TVSet)
{
TVSet t =(TVSet)o;
if(price == t.price && brand == t.brand)
return true;
}
return false;
}
}
这是我的学校作业,告诉我们写一个封装电视机概念的类,假设电视机具有以下属性:品牌(可空字符串,默认为空)和价格(a非负十进制数,默认为 0)。请遵循命名约定来开发课程,包括 - 默认构造函数 - 以品牌和价格为参数的构造函数 - 访问器方法和修改器方法 - toString 方法返回由 (1) 品牌 (2) 逗号和 (3) 价格组成的字符串(四舍五入到小数点后第二位) - 等于方法 - 每当提供无效值时,将一行错误消息“INVALID VALUE”打印到标准输出流。 equals(Object o)有什么用?
【问题讨论】:
-
默认构造函数仅在类不提供时存在。如果它提供任何构造函数,即使是无参数的构造函数,它也不是默认构造函数。您没有遵循方法
TVSet的命名约定,实际上也没有遵循任何非覆盖方法。 -
顾名思义,如果两个对象相等则返回
true。