1-9编程练习
来源:1-9 编程练习
慕神0457710
2020-08-04 23:53:00
public class Book {
private String name;//书名
private String author;//作者
private String press;//出版社
private double price;//价格
public String getPress() {
return press;
}
public void setPress(String press) {
this.press = press;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if (price > 10) {
this.price = price;
} else {
System.out.println("图书价格最低10元");
this.price = 10;
}
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
/**
* 有参构造方法对成员变量进行赋值
* @param name
* @param author
* @param press
* @param price
*/
public Book(String name, String author, String press, double price) {
this.name = name;
this.author = author;
this.press = press;
this.setPrice(price);
}
/**
* 信息介绍方法,描述图书所有信息
*/
public void introduce() {
System.out.println("书名:"+this.name);
System.out.println("作者:"+this.author);
System.out.println("出版社:"+this.press);
System.out.println("价格:"+this.price);
}
}public class BookTest {
public static void main(String[] args) {
Book book = new Book("红楼梦","曹雪芹","人民文学出版社",5);
book.introduce();
System.out.println("================================");
Book book1 = new Book("小李飞刀","古龙","中国长安出版社",55.5);
book1.introduce();
}
}1回答
同学你好,已完成练习,很棒!
不过有一个小建议,建议创建无参构造。因在一个java类中如果没有写构造方法,JVM(Java虚拟机)会默认添加一个无参构造方法,但是当写了有参构造后,JVM(Java虚拟机)不会再默认添加一个,如果只写了一个带参构造,假如有一个子类继承了它,一般子类的无参构造默认去调用的是父类的无参构造(而此时父类并没有无参构造),这个时候就会报错了。所以无论用或不用都建议同学把无参构造写上,这是一个良好的编码习惯。
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题