Sub topic 3
Creating Objects with new and Accessing Members
A class is a definition for a kind of object. An object is one usable instance, or copy, made from that definition. For example, a Book class can describe many books, while each Book object can have its own title and page count.
An object’s fields hold its data. Its methods are actions it can perform. To use a field or method, you usually put a dot between the object’s name and the member’s name. A member is a field or method that belongs to a class.
Create and use two books
This program creates two Book objects. It sets their fields, reads a field, and calls methods on each object.
Save the code in a file named Main.java:
class Book {
String title;
int pages;
void describe() {
System.out.println(title + " has " + pages + " pages.");
}
void addPages(int added) {
pages = pages + added;
}
}
public class Main {
public static void main(String[] args) {
Book guide = new Book();
guide.title = "Trail Guide";
guide.pages = 120;
System.out.println("Starting pages: " + guide.pages);
guide.describe();
guide.addPages(8);
guide.describe();
Book cookbook = new Book();
cookbook.title = "Kitchen Notes";
cookbook.pages = 200;
cookbook.describe();
}
}Here, String is a type for text, and int is a type for whole numbers. The word void means that a method does not return a value. System.out.println prints a line of text.
In a terminal, a program for typing commands, go to the folder containing Main.java. Run these commands:
javac Main.java
java MainThe first command compiles the code, which means it turns the source text into a form Java can run. The second command runs the program. You should see:
Starting pages: 120
Trail Guide has 120 pages.
Trail Guide has 128 pages.
Kitchen Notes has 200 pages.Follow object creation
Look at the first line inside main:
Book guide = new Book();This line does three things:
Book guidedeclares a variable namedguidethat can refer to aBook.new Book()creates aBookobject.=assigns the new object’s reference toguide. A reference is a value that lets the variable refer to an object.
The parentheses in new Book() call a constructor. A constructor is code that sets up a new object. Because Book declares no constructor, Java supplies one that takes no values between the parentheses.
Later, new Book() creates a second object for cookbook. Its fields are separate from the fields of the first object. Changing the page count of guide does not change the page count of cookbook.
Access fields and call methods
The dot selects a member of an object:
guide.title = "Trail Guide";stores text in thetitlefield.guide.pagesreads the value of thepagesfield when it appears in the print statement.guide.describe()calls thedescribemethod. The method reads the fields ofguideand prints them.guide.addPages(8)callsaddPagesonguide. The value8is an argument, a value passed into a method. The method adds it to that book’s page count.
The parentheses matter. A field access such as guide.pages does not use parentheses. A method call such as guide.describe() does, even when the method takes no arguments.
Avoid common mistakes
- Create the object with
newbefore trying to use its members. DeclaringBook guidealone does not create a book. - Use the correct object name before the dot. For example,
cookbook.describe()describes the cookbook, not the guide. - Match names and capital letters exactly.
pagesandPagesare different names in Java. - Use parentheses when calling a method, and put any arguments inside them.
Exercise
After the example runs, what does cookbook.pages contain? Why?
Show answer
It contains 200. The call to addPages changed guide, which is a separate Book object.
Exercise
What line would print the description of guide after adding another 10 pages to it?
Show answer
Use guide.addPages(10); followed by guide.describe();. It will print that Trail Guide has 138 pages.