针对限定作者、书名均为只读属性的代码及其疑问
package COM.JAVA;
public class First {
private String bname;
private String zname;
private String cname;
private double price;
public String getBname() {
return bname;
}
public String getZname() {
return zname;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public double getPrice() {
return price;
}
public First(String bname,String zname, String cname,double price) {
this.bname=bname;
this.zname=zname;
this.cname=cname;
if(price<10) {
System.out.println(“图书价格最低10元”);
price=10;
this.price=price;
}else {
this.price=price;
}
}
}
这里在构造函数里面加if可以实现对price的改变,也别忘记赋值。
package COM.JAVA;
public class FirstTest {
public static void main(String[] args) {
First one=new First("红楼梦","曹雪芹","人民文学出版社",9);
First two=new First("小李飞刀","古龙","中国长安出版社",55);
System.out.println(one.getBname());
System.out.println(one.getZname());
System.out.println(one.getCname());
System.out.println(one.getPrice());
System.out.println("==================");
System.out.println(two.getBname());
System.out.println(two.getZname());
System.out.println(two.getCname());
System.out.println(two.getPrice());
}
}
这里还是请教一下大佬,是否删除set就等于改为只读属性了吗?