封装 编程练习1-7后续
public class Book {
//私有属性:书名、作者、出版社、价格
private String name,author,publication;
private double price;
//通过构造方法实现属性赋值
public Book(String name, String author, String publication, double price){
this.name=name;
this.author=author;
//this.publication=publication;
//this.price=price;
//this.setName(name); //?????
// this.setAuthor(author);
this.setPublication(publication);
this.setPrice(price);
}
// set/get 设定
//限定作者为只读属性
public String getName(){
return this.name;
}
//限定书名均为只读属性
public String getAuthor(){
return this.author;
}
////////////////////////////
public String getPublication(){
return this.publication;
}
public void setPublication(String publication){
this.publication=publication;
}
public double getPrice(){
return this.price;
}
public void setPrice(double price){
if(price<10.0){
System.out.println("图书价格最低10元");
this.price=10.0; //注意此处需要加上this
}
else{
this.price=price;
}
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
//信息介绍方法,描述图书所有信息
public void information(){
System.out.println("书名:"+this.name);
System.out.println("作者:"+this.author);
System.out.println("出版社:"+this.publication);
System.out.println("价格:"+this.getPrice()+"元");
}
}public class BookTest {
// 测试方法
public static void main(String[] args) {
//实例化对象,调用相关方法实现运行效果
Book one=new Book("红楼梦", "曹雪芹","人民文学出版社",9.0);
Book two=new Book("小李飞刀", "古龙","中国长安出版社",55.5);
//Book one=new Book(9.0);
// one.setName("红楼梦");
// one.setAuthor("曹雪芹");
// one.setPublication("人民文学出版社");
// one.setPrice(10.0);
one.information();
System.out.println("================================");
two.information();
}
}请问为何get方法处写
public String getName(){
return name;
}或者是
public String getName(){
return this.name;
}都可以正常运行?但是考虑到代码的安全性,应该使用 return this.name; 这种形式吧?要是使用return name; 这种形式,那就是在使用get()方法取值的时候,没有起到封装的作用了吧?谢谢。
1
收起
正在回答 回答被采纳积分+1
1回答
chrismorgen
2019-01-14 10:04:17
是的,都可以返回name,也是起到了封装的作用,同学所说的就是一个带this,而一个不带this,this指的是本类的实例,那么看以this.name和name的区别,this.name指的是通过本类的对象调用name成员,name是本类的成员,所以两者本类本质上并无差别,他俩都是安全的,安不安全取决于修饰成员的关键字,譬如private就是安全的,只能通过getter方法来获取类的成员属性,祝学习愉快~
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星