关于1-5编程练习,作者/书名均为只读属性,我这么写总感觉怪怪的
public class Book {
//私有属性:书名、作者、出版社、价格
private String name;
private String author;
private String publisher;
private float price;
//通过构造方法实现属性赋值
public String getName(String name){
return this.name = name;
}
public String getAuthor(String author){
return this.author = author;
}
public void setPublisher(String publisher){
this.publisher = publisher;
}
public String getPublisher(){
return this.publisher;
}
public void setPrice(float price){
if(price < 10.0f){
System.out.println("图书价格最低10元");
this.price = 10.0f;
}else
this.price = price;
}
public float getPrice(){
return this.price;
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
//信息介绍方法,描述图书所有信息
public void show(){
System.out.println("书名:"+this.name);
System.out.println("作者:"+this.author);
System.out.println("出版社:"+this.publisher);
System.out.println("价格:"+this.price+"元");
}
}
public class BookTest {
// 测试方法
public static void main(String[] args) {
//实例化对象,调用相关方法实现运行效果
Book book1 = new Book();
book1.getName("红楼梦");
book1.getAuthor("曹雪芹");
book1.setPublisher("人民文学出版社");
book1.setPrice(5.0f);
book1.show();
System.out.println("=======================");
Book book2 = new Book();
book2.getName("小李飞刀");
book2.getAuthor("古龙");
book2.setPublisher("中国长安出版社");
book2.setPrice(55.5f);
book2.show();
}
}28
收起
正在回答
3回答
你好,你可以在Book类中创建带参构造方法,在测试类中通过带参构造方法创建对象完成属性的初始化,输出的时候,调用show方法,但是建议show方法中调用属性时使用getter方法,更加规范。祝学习愉快~
Ryne_Chen
2017-11-02 13:03:23
public class Book {
//私有属性:书名、作者、出版社、价格
private String name;
private String author;
private String publisher;
private float price;
//通过构造方法实现属性赋值
public Book(String name,String author,String publisher) {
this.name = name;
this.author = author;
this.publisher = publisher;
}
public String getName(){
return this.name;
}
public String getAuthor(){
return this.author;
}
public void setPublisher(String publisher){
this.publisher = publisher;
}
public String getPublisher(){
return this.publisher;
}
public void setPrice(float price){
if(price < 10.0f){
System.out.println("图书价格最低10元");
this.price = 10.0f;
}else
this.price = price;
}
public float getPrice(){
return this.price;
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
//信息介绍方法,描述图书所有信息
public void show(){
System.out.println("书名:"+this.getName());
System.out.println("作者:"+this.getAuthor());
System.out.println("出版社:"+this.getPublisher());
System.out.println("价格:"+this.getPrice()+"元");
}
}
/////////////////////////////
public class BookTest {
// 测试方法
public static void main(String[] args) {
// 实例化对象,调用相关方法实现运行效果
Book book1 = new Book("红楼梦", "曹雪芹", "人民文学出版社");
book1.setPrice(5.0f);
book1.show();
System.out.println("=======================");
Book book2 = new Book("小李飞刀", "古龙", "中国长安出版社");
book2.setPrice(55.5f);
book2.show();
}
}
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星