大神,帮我看下这段代码,不理解只读属性的概念。

大神,帮我看下这段代码,不理解只读属性的概念。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.imooc.mathod;
 
public class Book {
private String name;
private String author;
private String company;
private double price;
 
public Book(String name,String author,String company, double price) {
this.setPrice(price);
this.setCompany(company);
this.name=name;
this.author=author;
 
 
}
 
public String getCompany() {
return company;
}
 
public void setCompany(String company) {
this.company = company;
}
 
public double getPrice() {
return price;
}
 
public void setPrice(double price) {
if (price <= 10) {
System.out.println("最低价格不得低于10元");
this.price = 10;
 
 
 
}
 
public String getName() {
return name;
}
 
public String getAuthor() {
return author;
}
 
public void introduction() {
System.out.println("书名:" this.getName());
System.out.println("作者:" this.getAuthor());
System.out.println("出版社:" this.getCompany());
System.out.println("价格:" this.getPrice());
 
}
}
  1. 作业要求作者和书名都是只读属性,根据课程讲的,只读属性意思是修改不了系统属性

  2. 那么this.name=name;
    this.author=author;不就是直接修改系统属性了吗?而且还能任意填写信息。



正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
Scorp_ 2018-05-25 14:17:33
1
2
3
4
5
6
public Book(String name,String author,String company, double price) {
this.setPrice(price);
this.setCompany(company);
this.name=name;
this.author=author;
}

this.name 和 this.author 都是在调用构造方法的里面调用的    你只有在实例化对象的时候才能够设置书名和作者   而不能在main方法里更改  

  • 提问者 广州麻辣牛杂档 #1
    不明白啊啊
    2018-05-25 16:14:42
  • Scorp_ 回复 提问者 广州麻辣牛杂档 #2
    private的特点是只能被自己这个类访问和修改 也就是你只能在class这个类里访问属于这个类的私有属性 无论是你的构造方法还是getter ,setter方法都是通过调用属于这个类的方法来获取和更改带有私有属性的值 都是在这个类里的获取和修改 你在别的包里只能通过调用属于book类的方法来获取和更改它的私有属性而不能直接访问
    2018-05-25 16:25:48
  • Scorp_ 回复 提问者 广州麻辣牛杂档 #3
    说白了就是book构造方法this.name=name; this.author=author;其实就是在类里面改的 而private是不让类外面的改 所以你可以改啊
    2018-05-25 16:28:38
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师
插入代码