定义一个Book类,具有bookName(书名)、author(作者)和price(价格)三个属性,写现类的封装性。在类中添加一个无参构造,和一个有参构造方法。创建两个不同的对调用这两个构造方法(重载)。并输出书名、作者和价格(作者为本人姓名)。
package five;
public class Book {
private String bookname;
private String author;
private int price;
private String getPrice;
public Book() {
}
public Book (String bookname,String author,int price) {
this.bookname=bookname;
this.author=author;
this.price=price;
}
public String getBookname() {
return bookname;
}
public void setBookname() {
this.bookname=bookname;
}
public String getAuthor() {
return author;
}
public void setAuthor() {
this.author=author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price=price;
}
@Override
public String toString() {
return "书名="+bookname+","+"作者="+author+","+"价格="+price ;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Book b1=new Book();
b1.bookname="Tang";b1.author="Zhangsan";b1.price=30;
Book b2=new Book("Weng","Lisi",25);
System.out.println("b1相关信息");
System.out.println("书名="+bookname+","+"作者="+author+","+"价格="+price);
System.out.println("书名="+b1.getBookname()+","+"作者="+b1.getAuthor()+","+"价格="+b1.getPrice);
System.out.println(b1);
}
}
上面是私有成员变量了,这里用set方法,赋值给变量
你的Book类创建的是正确的,但是不应该直接在Book类执行main,因为这里面看不出私有变量和构造函数的作用和区别
你应该创建一个新的测试类然后创建Book对象