定义一个Document类,包含成员属性name,从Document派生出Book子类,增加pageCount属性,编写一个应用程序,测试定义的类。
时间: 2024-10-10 18:12:25 浏览: 66
定义一个基本的 `Document` 类如下:
```java
public class Document {
private String name;
// Constructor
public Document(String name) {
this.name = name;
}
// Getter and Setter for name
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
```
然后我们可以从 `Document` 类派生出 `Book` 子类,增加 `pageCount` 属性:
```java
public class Book extends Document {
private int pageCount;
// Constructor with both name and page count
public Book(String name, int pageCount) {
super(name); // Call the parent constructor
this.pageCount = pageCount;
}
// Getter and Setter for pageCount
public int getPageCount() { return pageCount; }
public void setPageCount(int pageCount) { this.pageCount = pageCount; }
}
```
接下来我们可以创建一个简单的应用程序来测试这两个类:
```java
public class Main {
public static void main(String[] args) {
// Create a book object
Book book = new Book("Python Programming", 450);
// Test methods
System.out.println("Book Name: " + book.getName());
System.out.println("Number of Pages: " + book.getPageCount());
// Modify the book's properties
book.setName("Introduction to Java");
book.setPageCount(500);
// Print updated information
System.out.println("Modified Book Name: " + book.getName());
System.out.println("Updated Number of Pages: " + book.getPageCount());
}
}
```
运行此程序会展示书名和页数,以及修改后的信息。这就是如何定义和测试 `Document` 和 `Book` 类的一个简单示例。
阅读全文