编写一个BookDemo类,实例化一个Book对象并显示,用java运行结果
时间: 2023-06-14 22:02:56 浏览: 92
以下是BookDemo类的示例代码:
```java
public class BookDemo {
public static void main(String[] args) {
// 实例化一个Book对象
Book book = new Book("Java Programming", "John Smith", 2021, 39.99);
// 输出Book对象信息
System.out.println("Book Information:");
System.out.println("Title: " + book.getTitle());
System.out.println("Author: " + book.getAuthor());
System.out.println("Year: " + book.getYear());
System.out.println("Price: $" + book.getPrice());
}
}
```
在运行该代码之前,需要确保Book类已经被定义。Book类的代码如下:
```java
public class Book {
private String title;
private String author;
private int year;
private double price;
public Book(String title, String author, int year, double price) {
this.title = title;
this.author = author;
this.year = year;
this.price = price;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public int getYear() {
return year;
}
public double getPrice() {
return price;
}
}
```
在运行BookDemo类后,控制台会输出以下结果:
```
Book Information:
Title: Java Programming
Author: John Smith
Year: 2021
Price: $39.99
```
阅读全文