In the last chapter, we imported a few objects from Java’s “standard library”: the collection of classes and methods that are pre-built by the creators of the language.
In this chapter, we will create objects of our own, and each one will contain a single method.
Type up the following code and get it to compile. Save it in your ‘javahard2’
folder with a name of
Lines 1-5 define an object called
Cow. The definition of the Cow class
includes the definition of a method called
moo(). Note that on line 2 it
says “public void moo()”, not “public static void moo()”. Except for main(),
you won’t be using the keyword static very much anymore.
Lines 7 through 11 define a class named
Pig, containing an
And lines 13 through 17 define a class named
Duck, which contains a
Lines 19 to 34 define the class that matches the name of the Java
file. Notice that in this file, the class
OldMacDonald has the keyword
public in front, but none of the other classes do. In Java, each file
may only have one public class in it, and the name of that public class
has to match the name of the file.
This class contains the
main() method in it, which is where the Java Virtual
Machine begins when executing a file. The
OldMacDonald class is listed
after the other classes in the file, but it would work the same if the classes
were in a different order.
When we run this program, execution begins on the first line of the main()
method. Any other code in the file will only execute if it gets called from
Lines 22 and 23 instantiate two
Cow objects. Lines 24 and 25 call the
method on behalf of each object. This causes execution to jump up to line 3,
run the println() statement inside the method, and return back down below.
On line 27 we create an instance of a
Pig object and then call its
method twice. And on line 31 we instantiate a
Duck object and call its only
method on the next line.
Then on line 33 we hit the close curly brace of the
main() method, which
typically means the end of the program.
Do you see? Defining your own objects isn’t so hard, and calling their methods is pretty easy, too, once you’ve instantiated an object.
“Learn Object-Oriented Java the Hard Way” is ©2015–2016 Graham Mitchell