编写类book,定义方法updatePrice,实现更改某本书的价格,具体,如果价格>150,则更改为150,如果价格>100,更改为100,否则不变
-
思路:
-
类名: book
-
方法名: updatePrice
-
返回值: int
-
方法的形参: ()
-
属性: price name
-
提供一个构造器
package Hello;
public class a {
public static void main(String[] args) {
book books = new book("jjj",300);
books.info();
//更新价格
books.updatePrice();
books.info();
}
}
class book{
String name;
double price;
public book(String name, double price){
this.name = name;
this.price = price;
}
public void updatePrice() {
//如果方法中,没有price局部变量,this.price 等价price
if (this.price > 150){
this.price = 150;
}else if (this.price > 100 ){
this.price = 100;
}
}
//显示书籍的情况
public void info(){
System.out.println("书名="+ this.name +"价格=" + this.price);
}
}
-
toString方法
package Hello;
public class a {
public static void main(String[] args) {
book books = new book("jjj",300);
books.info();
//更新价格
books.updatePrice();
books.info();
}
}
class book {
String name;
double price;
public book(String name, double price) {
this.name = name;
this.price = price;
}
public void updatePrice() {
//如果方法中,没有price局部变量,this.price 等价price
if (this.price > 150) {
this.price = 150;
} else if (this.price > 100) {
this.price = 100;
}
}
//显示书籍的情况
public void info() {
// System.out.println("书名=" + this.name + "价格=" + this.price);
System.out.println(this);
}
@Override
public String toString() {
return "book{" + "书名=‘ " + name + '\'' + ",价格=" + price + '}';
}
}