获取值和输入值的时候用set/get方法和直接用this.属性名得到的结果不是一样吗。
来源:1-9 编程练习
sx1011
2020-08-08 17:11:53
public class Book {
private String name;
private String editor;
private String saler;
private double price;
public Book() {
}
public Book(String name, String editor, String saler, double price) {
this.name = name;
this.editor = editor;
//System.out.println("不用set方法");
this.saler = saler;
this.price = price;
//System.out.println("用set方法");
this.setSaler(saler);
this.setPrice(price);
}
// 定义信息公示方法
public void infor() {
System.out.println("书名:" + this.name);
System.out.println("作者:" + this.editor);
System.out.println("不用get方法");
System.out.println("出版社:" + this.saler);
System.out.println("价格:" + this.price + "元");
System.out.println("用get方法");
System.out.println("出版社:" + this.getSaler());
System.out.println("价格:" + this.getPrice() + "元");
}
public String getName() {
return this.name;
}
public String getEditor() {
return this.editor;
}
public String getSaler() {
return this.saler;
}
public double getPrice() {
return this.price;
}
public void setSaler(String saler) {
this.saler = saler;
}
public void setPrice(double price) {
if (price <= 10) {
this.price = 10;
System.out.println("图书最低价格10元");
} else {
this.price = price;
}
}
}public class BookTest {
public static void main(String[] args) {
Book b = new Book("红楼梦", "曹雪芹", "人民文学出版社", 10);
Book b1 = new Book("小李飞刀", "古龙", "中国长安出版社", 55.5);
b.infor();
System.out.println("======================");
b1.infor();
}
}get/set方法和this.属性名主要的区别怎么用代码体现
2回答
属性是private私有的,外部程序访问不到。
对外的接口是public公共的get/set方法和构造函数。
打个比方,景点购票,游客(外部程序)要购票,景区有两个窗口,一个窗口卖团体票(构造函数,一次赋值多个属性),一个窗口卖散票(set/get方法,一次只能赋值一个属性),只有窗口工作人员才能访问票库(私有属性,this.属性名)。
导游去买团体票,那团体票的窗口肯定从票库(私有属性)取票,不可能团体票的窗口的工作人员再跑去散票窗口去拿票吧(所以一般构造函数直接调用this.属性名赋值)。
票库(私有属性,this.属性名)只能由这两个购票窗口(set/get方法和构造函数)访问,游客(外部程序)不能直接访问。
好帮手慕阿园
2020-08-08
同学你好,上面同学说法是正确的,可以参考
如果set方法中没有逻辑判断,那么结果都是一样的哦;但是在本题中是不一样的,因为在set方法中对价格进行判断,如果小于10,就把价格设置成默认值10,如果在构造方法中不使用set方法,那么这个判断就是无效的
至于为什么同学这里输出都是一样的,是因为同学同时调用了this.属性名和set方法,set方法也生效了,所以结果是一样的,同学可以把set方法注释掉,在测试类中把价格设置成低于10的,看看输出结果
如下,对于价格的判断并没有生效,这也是使用set方法和this.属性名的区别

同学也可以自己动手试一下哦
祝学习愉快
相似问题