書包:
這個範例會建立一個名為 bookpack 的包,其中包含一個用於管理書籍資料庫的簡單類別。
圖書課程:
它有私有屬性 title、author 和 pubDate(標題、作者和出版日期)。
構造方法初始化屬性。
show() 方法顯示書籍詳細資料。
圖書示範課程:
建立一個包含 5 個 Book 物件的陣列。
用書籍資訊填滿陣列並使用 show() 方法顯示詳細資訊。
程式碼範例
目錄結構:
src/ bookpack/ BookDemo.java
// Demonstração breve dos pacotes. package bookpack; class Book { private String title; private String author; private int pubDate; // Construtor Book(String t, String a, int d) { title = t; author = a; pubDate = d; } // Método para exibir os detalhes do livro void show() { System.out.println(title); System.out.println(author); System.out.println(pubDate); System.out.println(); } } // Classe para demonstrar o uso de Book class BookDemo { public static void main(String args[]) { Book books[] = new Book[5]; // Cria uma matriz de objetos Book // Preenche a matriz com diferentes livros books[0] = new Book("Java: A Beginner's Guide", "Schildt", 2014); books[1] = new Book("Java: The Complete Reference", "Schildt", 2014); books[2] = new Book("The Art of Java", "Schildt and Holmes", 2003); books[3] = new Book("Red Storm Rising", "Clancy", 1986); books[4] = new Book("On the Road", "Kerouac", 1955); // Exibe os detalhes de cada livro for (int i = 0; i < books.length; i++) { books[i].show(); } } }
編譯執行
javac bookpack/BookDemo.java
java bookpack.BookDemo
重要說明:
預期輸出:
Java: A Beginner's Guide Schildt 2014 Java: The Complete Reference Schildt 2014 The Art of Java Schildt and Holmes 2003 Red Storm Rising Clancy 1986 On the Road Kerouac 1955
以上是簡要封裝範例的詳細內容。更多資訊請關注PHP中文網其他相關文章!