1、 编写一个类 Book,代表图书: 具有属性: 名称(title)、页数(pageNum),其中页数不能 少于 200 页,否则输出错误信息,并赋予默认值 200。 具有方法: 为各属性设置赋值和取值方法。 detail,用来在控制 台输出每本图书的名称和页数 编写测试类 BookTest 进行测试:为 Book 对象的属性赋予初始 值,并调用 Book 对象的 detail 方法,看看输出是否正确
package part2;
/*1、 编写一个类 Book,代表图书:
具有属性: 名称(title)、页数(pageNum),其中页数不能
少于 200 页,否则输出错误信息,并赋予默认值 200。
具有方法: 为各属性设置赋值和取值方法。 detail,用来在控制
台输出每本图书的名称和页数
编写测试类 BookTest 进行测试:为 Book 对象的属性赋予初始
值,并调用 Book 对象的 detail 方法,看看输出是否正确*/
public class BookTest {
public static void main(String[] args) {
book b = new book();
b.setTitle("红楼梦");
b.setPageNum(20);
b.detail();
}
}
class book{
String title;
int pageNum;
public book() {
}
public book(String title, int pageNum) {
this.title = title;
this.pageNum = pageNum;
}
public void setTitle(String title) {
this.title = title;
}
public void setPageNum(int pageNum) {
if (pageNum<200){
System.out.println("页码错误,默认值为:"+pageNum);
this.pageNum=200;
}else {
this.pageNum = pageNum;
}
}
public String getTitle() {
return title;
}
public int getPageNum() {
return pageNum;
}
void detail(){
System.out.println("图书名称:"+getTitle());
System.out.println("页数:"+getPageNum());
}
}
2. 通过类描述xxx的 Java 学员。 具有属性: 姓名,年龄,性别,爱好,公司(都是:xxx
), 学科(都是:Java 学科)。 思考:请结合 static 修饰属性进行更好的类设计。
package part2;
public class Test3 {
public static void main(String[] args) {
Student s1 = new Student("张三", '男',18, "rap");
Student s2 = new Student("李四", '男',16, "打篮球");
Student s3 = new Student("王五", '男',28, "踢足球");
s1.info();
s2.info();
s3.info();
}
}
class Student {
private String name;
private int age;
private char sex;
private String hobby;
static String company = "xxx";
static String subject = "java";
Student(){
}
Student(String name,char sex,int age,String hobby){
this.name = name;
this.sex = sex;
this.age = age;
this.hobby = hobby;
}
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 char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public void info() {
System.out.println("姓名:" + name + ",性别:" + sex + ",年龄:" + age + ",爱好:" + hobby + ",公司:" + company + ",课程:" + subject );
}
}
3. 通过类描述衣服, 每个衣服对象创建时需要自动生成一个序号值。 要 求:每个衣服的序号是不同的, 且是依次递增 1 的。
package part2;
public class Test2 {
public static void main(String[] args) {
Clothes clothes = new Clothes();
Clothes clothes1 = new Clothes();
Clothes clothes2 = new Clothes();
}
}
class Clothes{
static int num = 0;
public Clothes() {
num++;
System.out.println(num);
}
}