封装中限制只读属性
来源:1-9 编程练习
慕无忌2118164
2021-03-01 11:59:56

如何限制为只读属性?如果限制成只读属性,岂不是不能set了?
而且构造函数初始化的时候一定会要set呀
相关代码:
public class Book {
private String bookname;
private String writer;
private String publish;
double price;
public void setBookname(String bookname) {
this.bookname = bookname;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getBookname() {
return bookname;
}
public String getWriter() {
return writer;
}
public String getPublish() {
return publish;
}
public void setPublish(String publish) {
this.publish = publish;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if(price<=10)
{
System.out.println("图书价格最低10元");
this.price=10;
}
else {
this.price = price;
}
}
public Book(String bookname,String writer,String publish,double price) {
this.setBookname(bookname);
this.setWriter(writer);
this.setPublish(publish);
this.setPrice(price);
}
public void BookDisplay() {
System.out.println("书名:"+this.bookname);
System.out.println("作者:"+this.writer);
System.out.println("出版社:"+this.publish);
System.out.println("价格:"+this.price+"元");
}
}
1回答
好帮手慕小脸
2021-03-01
同学你好,
1、如何限制为只读属性?如果限制成只读属性,岂不是不能set了?
1)只设置get()方法即可
2)是的,不能写set()
2、构造函数初始化的时候一定会要set呀
并不是一定会要set()方法,这里书名和作者并没有任何逻辑判断,所以写成this.name=name也是可以的,如下:

祝学习愉快~
相似问题