針對限定作者、書名均為只讀屬性的程式碼及其疑問

Emin1em11111發表於2020-10-29

針對限定作者、書名均為只讀屬性的程式碼及其疑問

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就等於改為只讀屬性了嗎?

相關文章