1. 编写一个类 Book,代表图书。 具有属性: 名称(title)、页数(pageNum),其中页数不能少于 200 页,否则输出错误信息,并赋予默认值 200。 具有方法: 为各属性设置赋值和取值方法。 detail,用来在控制台输出每 本图书的名称和页数 编写测试类 BookTest 进行测试:为 Book 对象的属性赋予初始值,并调 用 Book 对象的 detail 方法,看看输出是否正确
public class BookTest1 {
public static void main(String[] args) { // TODO Auto-generated method stub Book a1 = new Book("哈利波特",180); a1.detail(); }
} class Book{ private String title; private int pageNum; public Book(String title,int pageNum) { this.title = title; this.setPageNum(pageNum); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { if(pageNum<200) { System.out.println("页数不能少于200页!"); this.pageNum = 200; } else { this.pageNum = pageNum; } } public void detail(){ System.out.println("书名:" + title + ",页数:" + pageNum); } }
通过类描述开课吧的 Java 学员。 具有属性: 姓名,年龄,性别,爱好,公司(都是:开课吧),学科(都 是:Java 学科)。 思考:请结合 static 修饰属性进行更好的类设计。
public class Javastudent {
public static void main(String[] args) { // TODO Auto-generated method stub Student a1 = new Student("张三",18,"男","打篮球"); Student a2 = new Student("李四",20,"男","打游戏"); a1.detail(); a2.detail(); }
} class Student{ static String subject; static String company; private String name; private int age; private String sex; private String hobby; public Student(String name,int age,String sex,String hobby) { this.name = name; this.age = age; this.sex = sex; this.hobby = hobby; subject = "Java学科"; company = "开课吧"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } public void detail(){ System.out.println("名字:" + name + ",年龄:" + age+",性别:"+sex+",兴趣:"+hobby+",学科:"+subject+",公司:"+company); } }
通过类描述衣服, 每个衣服对象创建时需要自动生成一个序号值。 要求:每个衣服的序号是不同的, 且是依次递增 1 的。
package lok1;
public class Jacaclothes {
public static void main(String[] args) { // TODO Auto-generated method stub Clothes a1 = new Clothes(); Clothes b1 = new Clothes(); Clothes c1 = new Clothes(); a1.nums(); b1.nums(); c1.nums(); }
} class Clothes{ private static int num = 1; private int number ; public Clothes(){ this.number = Clothes.num; Clothes.num++; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public void nums() { System.out.println("序号为:"+number); } }