以下是另一个Java面向对象示例,其中包含一个对象数组:
class Book { String title; String author; int year; public Book(String title, String author, int year) { this.title = title; this.author = author; this.year = year; } public String getTitle() { return title; } public String getAuthor() { return author; } public int getYear() { return year; } } public class Example { public static void main(String[] args) { Book[] library = new Book[3]; library[0] = new Book("The Great Gatsby", "F. Scott Fitzgerald", 1925); library[1] = new Book("To Kill a Mockingbird", "Harper Lee", 1960); library[2] = new Book("1984", "George Orwell", 1949); // Print out the title, author, and year of each book in the library for (Book book : library) { System.out.println("Title: " + book.getTitle() + "\nAuthor: " + book.getAuthor() + "\nYear: " + book.getYear() + "\n"); } } }
在这个例子中,我们定义了一个Book类,每个Book对象都有一个标题、作者和出版年份。我们创建了一个Book对象数组,library,其中包含三本书。我们使用new关键字实例化了每个Book对象并将它们存储在数组中。
Book
library
new
然后我们循环遍历library数组,并使用getTitle()、getAuthor()和getYear()方法打印出每本书的标题、作者和出版年份。
getTitle()
getAuthor()
getYear()
另一个Java面向对象示例,其中包含一个对象数组和一些对象方法:
class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } public void sayHello() { System.out.println("Hello, my name is " + name + "."); } public void celebrateBirthday() { age++; System.out.println(name + " is now " + age + " years old."); } } public class Example { public static void main(String[] args) { Person[] family = new Person[3]; family[0] = new Person("John", 30); family[1] = new Person("Jane", 25); family[2] = new Person("Jim", 10); // Say hello to each family member for (Person person : family) { person.sayHello(); } // Celebrate everyone's birthday for (Person person : family) { person.celebrateBirthday(); } } }
在这个例子中,我们定义了一个Person类,每个Person对象都有一个名字和年龄。我们创建了一个Person对象数组,family,其中包含三个人。我们使用new关键字实例化了每个Person对象并将它们存储在数组中。
Person
family
然后我们循环遍历family数组,并使用sayHello()方法向每个家庭成员打招呼。接着我们循环遍历family数组,并使用celebrateBirthday()方法庆祝每个人的生日。celebrateBirthday()方法会将年龄增加1,并打印出新的年龄。
sayHello()
celebrateBirthday()
原文链接:codingdict.net