编写一个类Book,代表教材:
具有属性:名称(title)、页数(pageNum)、种类(type)
具有方法:detail,用来在控制台输出每本教材的名称、页数、 种类
具有两个带参构造方法:第一个构造方法中,设置教材种类为“ 计算机”(固定),其余属性的值由参数给定;第二个构造方法 中,所有属性的值都由参数给定
•编写测试类BookTest进行测试:
分别以两种方式完成对两个Book3对象的初始化工作,并分别调 用它们的detail方法,看看输出是否正确这个是老师的作业,其中构造方法不太懂,求高手给代码。

解决方案 »

  1.   

    public class Book{//示例,只是示例
    String title;
    int pageNum;
    int type;
    public Book(int pageNum,int type){//这就是传说中的构造方法。
    this.title ="计算机";
    this.pageNum = pageNum;
    this.type = type;
    }
    }
      

  2.   

    public class Test24 { public static void main(String[] args) {

    Book book1 = new Book(100, 1);
    book1.detail();
    Book book2 = new Book("java", 200, 2);
    book2.detail();
    }
    }class Book {
    String title;
    int pageNum;
    int type; public Book(int pageNum, int type) {
    this.title = "计算机";
    this.pageNum = pageNum;
    this.type = type;
    }

    public Book(String title, int pageNum, int type){
    this.title = title;
    this.pageNum = pageNum;
    this.type = type;
    }

    public void detail(){
    System.out.println("名称:" + title + ", 页数:" + pageNum + ", 类型:" + type);
    }}
    构造方法没有返回值,方法名与类名相同!
      

  3.   

    public class Book{
        String title;
        int pageNum;
        String type;public Book(String titile,int pageNum){
        this.title=title;
        this.pageNum=pageNum;
        this.type="计算机";
    }public Book(String titile,int pageNum,String type){
        this.title=title;
        this.pageNum=pageNum;
        this.type=type;
    }
    }
      

  4.   

    不好意思,main方法和detail方法应该写在Book类里面public String detail(){
          System.out.println(this.title + "---" + this.pageNum + "---" + this.type);
    }public static void main(String[] args){
           Book book1 = new Book("book1",100);
           Book book2 = new Book("book2",200,"文学");
           book1.detail();
           book2.detail();}