MENU

构造一个简单java类

• November 14, 2020 • 面向对象编程

构造一个简单java类

练习构造一个基础的java类,由此来提升总结开发过程中需要注意的问题

class Book{
    private int id;
    private String name;
    private String auther;
    private double price;
    public Book(){       //空构造器
    }
    public Book(int id) {
        this(id,null,null,0.00);   //默认价格为0
    }
    public Book(int id, String name) {
        this(id,name,null,0.00);
    }
    public Book(int id, String name, String auther) {
        this(id,name,auther,0.00);
    }
    public Book(int id, String name, String auther, double price) {
        this.id = id;
        this.name = name;
        this.auther = auther;
        this.price = price;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuther() {
        return auther;
    }
    public void setAuther(String auther) {
        this.auther = auther;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
}

总结

  1. 类名称一定要有意义,可以明确描述某一类事物,比如 书(Book)
  2. 类中的所有属性必须使用private封装,保证安全性
  3. 类中可以有无数个构造方法,但是必须保留空构造方法
  4. 类中不允许出现任何的输出语句,所有获取必须返回,而不是打印
  5. (非必须)可以提供一个获取对象详细信息,暂时将方法名取为getInfo()

代码编译器:IntelliJ IDEA 2020.02

Archives QR Code Tip
QR Code for this page
Tipping QR Code