Java 对象组合示例:创建 Book 类并包含 Author 对象
以下是使用 Java 实现上述要求的代码示例:
class Author {
private String name;
private String nationality;
public Author(String name, String nationality) {
this.name = name;
this.nationality = nationality;
}
public String getName() {
return name;
}
public String getNationality() {
return nationality;
}
}
class Book {
private String title;
private Author author;
public Book(String title, Author author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public Author getAuthor() {
return author;
}
}
public class Main {
public static void main(String[] args) {
// 创建一个Author对象
Author author = new Author('John Doe', 'USA');
// 创建一个Book对象,将Author对象作为属性
Book book = new Book('The Great Adventure', author);
// 访问Book对象的属性
System.out.println('书名: ' + book.getTitle());
System.out.println('作者姓名: ' + book.getAuthor().getName());
System.out.println('作者国籍: ' + book.getAuthor().getNationality());
}
}
这段代码首先定义了一个名为Author的类,该类具有name和nationality私有属性,并且提供了构造方法和访问这些属性的方法。然后定义了一个名为Book的类,该类具有title和author私有属性,其中author属性的类型为Author类。在Book类中使用了对象组合,将一个Author对象作为属性。最后,在main方法中创建了一个Author对象和一个Book对象,并通过访问对象的方法来展示结果。
原文地址: https://www.cveoy.top/t/topic/n9W 著作权归作者所有。请勿转载和采集!