编写一个Book类,有name和pages两个属性,用java
时间: 2024-05-14 10:17:35 浏览: 110
以下是一个简单的Book类的Java示例,包含name和pages属性、构造函数和getter/setter方法:
```java
public class Book {
private String name;
private int pages;
public Book(String name, int pages) {
this.name = name;
this.pages = pages;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
}
```
可以使用如下代码创建一个Book对象,并设置其属性:
```java
Book book = new Book("Java Programming", 500);
book.setName("Java Programming 2nd Edition");
book.setPages(600);
System.out.println(book.getName()); // 输出:Java Programming 2nd Edition
System.out.println(book.getPages()); // 输出:600
```
阅读全文