A class defines the data and behavior of its objects. You can create an object using the new keyword, then access its fields and call its methods.
In this example, you will create two objects from a Book class. Each object stores its own title and author.
Source code
public class ObjectCreationExample {
void main() {
Book firstBook = new Book();
firstBook.title = "Learning Java";
firstBook.author = "Alice";
Book secondBook = new Book();
secondBook.title = "Exploring Java";
secondBook.author = "Bob";
firstBook.printDetails();
secondBook.printDetails();
}
}
class Book {
String title;
String author;
void printDetails() {
IO.println("Title: " + title);
IO.println("Author: " + author);
IO.println();
}
}
Explanation
The Book class declares two fields and one method:
class Book {
String title;
String author;
void printDetails() {
IO.println("Title: " + title);
IO.println("Author: " + author);
IO.println();
}
}
The fields title and author hold the data for each book. The printDetails() method prints that data.
The following statement creates a Book object:
Book firstBook = new Book();
Each part has a purpose:
| Part | Purpose |
|---|---|
Book |
Declares the variable’s type |
firstBook |
Names the variable that refers to the object |
new Book() |
Creates and initializes a new Book object |
Because Book does not declare a constructor, Java provides a default constructor with no parameters.
After creating the object, you can assign values to its fields using the dot operator:
firstBook.title = "Learning Java";
firstBook.author = "Alice";
You also use the dot operator to call a method:
firstBook.printDetails();
The second call to new Book() creates a separate object:
Book secondBook = new Book();
Each object has its own instance fields. Setting the title of secondBook does not change the title of firstBook.
Both classes are placed in the same source file. Only ObjectCreationExample is declared public, so the file is named ObjectCreationExample.java.
Run the example
Compile and run the file:
javac ObjectCreationExample.java
java ObjectCreationExample
Output
Title: Learning Java
Author: Alice
Title: Exploring Java
Author: Bob
This example assigns fields directly to show how objects work. In the next example, you will use a constructor to supply these values when creating each object.
