
Chunk 3, Module 1: Object-Oriented Java
Exploring object design by modeling real-world (doughy) Objects
Programmers solve technical problems in Java by creating and manipulating Java objects. Bruce Eckel, an extraordinary programming teacher and writer of our recommended text, describes an object like a fancy variable that can store multiple named chunks of data (called member variables) and also store Java code that manipulates that data.
To keep our introduction to Java objects gastronomically rich, this module will guide you through modeling a donut in code, creating instances of those donuts, and nibbling on them. In module 2, we'll model robotic dogs and feed our donuts to them.
prerequisites |
Confidence with our Chunk 1 and Chunk 2 modules will greatly aid your learning and synthesizing those core concepts. |
module
|
Module program overview |
prerequisites |
Confidence with our Chunk 1 and Chunk 2 modules will greatly aid your learning and synthesizing those core concepts. |
time considerations |
This is a fundamental module to your Java journey. Set aside 2-3 hours to read and ponder the resources links: your textbook, Bruce Eckle's book, and Oracle online. Then work through the core concepts and exercises. Finally dedicate 3-4 hours to programming your module project and preparing it for sharing. |
READ ME PLEASE resources |
Course Textbook - Java: Beginner's Guide Chapter 4 (First Half) . Chapter 4 starts with an introduction to Objects. Schildt reviews the core concepts of class structure from Module 2.3 and introduces the concept of Objects and how to create and manipulate them. Giving the whole chapter a read is worthwhile, but if you're feeling full of new content, you can safely stop reading at the section on "constructors". (6th ed, page 124). Oracle Online tutorial page "What is an Object?" which provides a concise example of Object design. Oracle Online tutorial page "What is a Class?" which connects object design to class structure. |
introducing bruce eckel! |
Bruce Eckel is a Java expert and extraordinary teacher. He takes care in his writing to explain the reasons and tradeoffs involved in using various architectural elements in Java. Notably, his books are free. You can download the 4th edition of his book Thinking in Java from our course server. Download Thinking In Java, 4th ed (2006)Eckel teaches object structure up front. Since this course has oriented toward the inverse philosophy of introducing objects after language fundamentals, we are just now at a point to start digging into Eckle's text. Sections to read:
Eckel is a broad thinker and speaker: his work addresses not only technical dimensions of programming but also the complexities of working in groups to make complicated outputs. Here's one of his lectures that discusses his book's development process, among other topics. |
setup your workspace |
Create a new package called objects1 and create the following empty class files for use throughout this tutorial:
|
"submitting" |
|
bookVIDEO! In-class lesson capture at CCAC: Object Introduction
The following film is a capture from the live Object-Oriented Java lesson. The video might be useful to watch before you dive in to get a conceptual overview.
A second set of clips of more in-depth discussion of Object design is embedded below.
arrow_upwardback up
bookKey points from resource readings
Notes for Java: A Beginner's Guide Chapter 4
This module builds on the concepts discussed in both the Java: A Beginner's Guide by Schildt and Bruce Eckel's Thinking In Java. It is vitally important that you ingest and digest this written content that your instructor has summarized the key points you should study in these readings before continuing on in the tutorials.
Notes for Eckle's Thinking In Java Chapter 1 and 2 Excerpts
Don't forget to study the chapters from Eckle's book linked as a PDF in the resources section above. Remember, Eckle is much more explanatory rather than factual in his writing, and so there's less code in his text and more discussion of what the key features of the code means.
arrow_upwardback up
extensionModule program concept overview
High level module goal
To solidify the concepts we discovered in the reading, this module guides your through building our own Object "model" in Java. Since donuts are tasty, and everybody likes donuts, and they provide a great case study in simple object design, the core of our program will involve planning and creating Donut objects.
Read the following program specification document carefully. You will be developing this program over the course of the module, so don't panic if the concepts referenced in the specs isn't familiar. The purpose is to create a mental "big-picture" view of where we're going, so we don't get lost in the details.
program goal |
Develop a simple program consisting of two Java classes which work together to create and manipulates Donut objects. The Donut class represents an actual physical donut and stores two pieces of information about itself: its name, and the percent of itself remaining to be eaten. The DonutLand class contains our program's main method and is responsible for creating and manipulating the instances of our Donut objects. Each Donut object provides a two-method interface: meaning each Donut object contains a method called void simulateEating(int biteSize) and int getPercRemaining(). |
why donuts? |
The better question is: why not? If we can model a donut, then anything that's like a donut we can probably model pretty easily, too. Most immediately, our donut manipulating code could be harnessed to create an inventory system for any number of organizations that track stuff that behave like a donut: loaves of bread, bunches of celery, or electron microscopes, etc. More generally, all Java objects contain the same fundamental guts. Instead of an object knowing how much of itself has been eaten, we could create objects that know, say, its host computer's geographic location, or the IP address of its transmitting machine. We'll start with the flour, sugar, butter, and baking powder of object-oriented Java and pastry deliciousness. |
high-level diagram |
Our program will involve two classes, one called Donut and the other called DonutLand. We will make instances of our Donut object inside the main method of DonutLand and explore their properties. ![]() |
sample program output |
Study the following program output from running DonutLand. We will make a Donut object, access one of its member variables, call a method on that same object, and then re-access the member variable to see how this Object can manage its own member variable state. ![]() |
access the exercise source |
arrow_upwardback up
extensionCore Concept 1: Donut Object Blueprints
The Object-Oriented (OO) programming approach
Object-oriented programming in Java remains a powerful problem-solving tool because human brains latch onto "things" that we can experience with our senses (hmmmm. raised-glazed donuts...) Further, humans make tools and use them an every conceivable domain to make new things, like sky scrapers, combs, and paper. This way of thinking about the world can be expressed in Java by creating our own type of data container, called an Object, that groups together data and operations on that data that are related in some way.
Setting up our class and file
Our module program specification calls for a Donut object. In order to make a digital donut object, we must create an instruction sheet for the compiler to use when doing so. This instruction sheet is contained inside a Java class that lives inside a file with a .java extension--exactly the same configuration as in previous modules.
If you didn't do so when noted the introductory sections of this module (it's okay :)), you may also need to first create the package objects1.

Code up our class Donut
Transfer this code exactly as shown into your NetBeans editor. Transfer the comments as well--your brain will thank you later. Don't forget to read the code as you transfer it!

What's new about our object-oriented class?
The difference between an object-oriented class (not a technical name) and ones like those in our previous modules is shown in two immediate ways:
- The class we'll turn into an object doesn't use the keyword static when declaring member variables and methods.
- They don't contain a main method. In other words, they aren't stand alone programs. We have to use them in some other class that does have a main method.
Our blueprint in a diagram
For the visual learners, the following diagram dissects our Donut blueprint class. It's worth a careful study:

arrow_upwardback up
extensionCore Concept 2: Creating instances of our Objects
Concept introductory video
The following clip from class recorded at CCAC's West Hills Center Spring of 18 dissects the object instantiation process in detail.
How do I use my blueprint to construct a Donut object?
We wrote nice looking code for our Donut objects, but it doesn't do anything yet. There's no main method in the class, so you'll notice you cannot successfully execute the class by clicking Run >> Run File as you usually can.
This makes conceptual sense because our Donut object doesn't really have anything to "do" by itself. Instead, it is like a data packaging tool that some other code can use to store information and actions related to a particular food product.
The class which uses our class Donut instructs the compiler to initiate the object construction. Java's keyword new is the trigger for the object creation process.
File setup review
Remember: our program now consists of two separate classes, each in their own file:
- Donut.java which contains a class that acts as a blueprint for creating Donut objects.
- DonutLand.java which contains a main method and statements that use new to instantiate (construct) Donut objects.
These two files work together to organize data about Donuts into neat and tidy objects. They don't need to be located in the same package, but in our example, they are organized this way.
Code up our class DonutLand
DonutLand is a simple class containing only a main method and a dozen or so statements. While short, it accomplishes a brand new task which is to create an instance of a Java object we designed and coded.
Transfer the following code for DonutLand.java into your NetBeans editor.

Review the code you just transferred carefully. Try to connect the comments you included above each statement with what you read about in our two reference texts. This is the core code to focus on in this module.
Since it has as main method, you can fire it up and send your program to the compiler. The output should be close to this:

Dissecting the object creation process
We can refer to DonutLand as the client of Donut.java. Just like a client uses a business to help him/her/them get something useful done, like ship a package to the Fiji islands, DonutLand uses Donut to organize information about a individual Donuts.
The power of new
Many important behind-the-scene moves are going down inside the compiler when the keyword new is encountered. Study the following dissection of these two lines.

arrow_upwardback up
extensionCore Concept 3: Accessing and manipulating Objects
Concept tutorial video
The following clip from class was recorded at CCAC's West Hills Center Spring of 18. We zoom into the way in which NetBean's code checker utility can show us how our "blueprint" objects and their member variables can be accessed from any given point in out code.
The magic . (dot) access operator
We want to internalize the use of the access operator . that we're using to access the Donut object's member variables and methods. Luckily, we access all Java object's member variables and methods using the . (dot) operator so once we learn the pattern, we can reuse it over and over again.
We're interested in the second pair of lines from DonutLand where we access both the member variable name and the method simulateEating(firstBiteSize):

Terminology Clarified
using handle variables |
Our variable firstDonut is special because it allows us to access any Donut object to which it points. The following figure shows how each method call and member variable read/write operation flows through firstDonut to get down to our object in the Heap. |
handle variables a.k.a |
The concept of a variable that stores the location of an object is common across many programming languages. They have several different names, but they all describe the same basic concept, so don't get confused. These terms are all, for our purposes, synonymous: handle variable = pointer variable = reference variable Your instructor has chosen to use the term Bruce Eckel used to use: handle variable because it describes very visually how we must have a way to touch and engage with the object, much like a physical handle allows us to open doors, cabinets, crates, etc. |
Flowchart of using firstDonut as a handle variable
This figure is very dense and was created as such to be accurate. Study it carefully by tracing all the lines that are associated with each step in our object creation and access process.

Notes on the figure
- Note that each method call down to Donut involves two lines: one for the call to the method, and one for the return of execution from the method back to the caller. A line that is solid represents that some value is passed to or from the method with this movement in code. A dotted line shows that only execution--no values--are moving between the caller and the method.
- Don't forget that our handle variables can point to any Donut object, and only Donut objects. Just like an int type variable can only store numbers without decimal points and String type variables only hold references to String objects, the type-checking system in Java enforces its rules on our newly created type Donut.
access the exercise source |
arrow_upwardback up
extensionExercise 0: Tracing execution flow through objects
Let's continue to explore how we can interact with our Donut objects. To help our brains visualize how the JVM executes our code, we're going to re-write the DonutLand class and add some calls to println() in our Donut "blueprint" class.
tip: copying classes before refactoring |
We're going to make major adjustments to our Donut and DonutLand classes. Since we don't want to zap the work we've already done to create well-commented example classes, let's make a copy of each of our classes and append "_Refactored to the end of each new class name. ![]() |
Refactoring our Donut method guts
Add the following printed annotations to our existing Donut class's methods:

Refactoring DonutLand's main method
Our original DonutLand class contained lots of comments. Our DonutLand_Refactored class is mostly bare Java code and a larger set of method calls to illustrate the way messages get passed between DonutLand and its Donut objects.
Since coding to a specification is a "gateway" Java skill, let's see how the refactoring we're about to undertake might be described:
program objective |
Demonstrate calls to all methods on Donut objects and visualize how they manipulate the member variables held privately by Donut. |
requirement 1: refactor printDivider |
There is repeated code in main used for printing out data retrieved from our objects. Refactor printDivider to be named printObjectData to accept a Donut object as an input parameter. The guts of the method should simply call appropriate methods and access member variables to display the value of all the data inside Donut. |
requirement 2: instantiate a second Donut |
Using the new keyword, create a second Donut object. Call its simulateEating method and pass it into our new printObjectData method to show that the method calls are working properly. |
requirement 3: tinker with method calls |
Create a few constants to represent different bite sizes. Use these when calling simulateEating(int bite) and show that the methods are working with calls to printObjectData. |
sample output |
The following output satisfies the above specification: |
Try it before checking the reference
Study the above specification and try coding a refactored DonutLand class before referencing the sample code accessible with the button below.
And our utility method:
access the exercise source |
Core Concept 4: Debriefing key points from our refactoring ex. 0
Passing "handles" to Donut objects as input parameters
We did something completely cool by declaring (Donut inputDonut) as our input parameter type and variable name to the method printObjectData: we are passing out own data type into a method.

Consider this strategy of writing methods as constructing custom messages to our method with the following contract: If the user of the method sends me a reference to a Donut object, I'll access each of its member variables and send those values to System.out.println() for display to the user.
Java passes by reference |
Our variables firstDonut and secondDonut are both what we're calling "handle" variables since they each allow us to access one of our two Donut objects. Let's really digest this: Study our two calls to printObjectData in which we are passing firstDonut or secondDonut as input parameters: ![]() and now a zoomed in look at the second call: ![]() Since firstDont and secondDonut connect to a single Donut instance (stored on the heap, in the RAM), we can use those objects as containers for data that we want all sorts of methods to interact with. In our case, the method printObjectData knows how to interact with Donut objects to accomplish a task: printing the member variable values. Each time we call this method, the local variable with the identifier inputDonut takes on the value of the handle variable we passed in when we called the method. Designing methods that take in entire objects as parameters is the fundamental way Java harnesses its object-orientedness. A Donut object contains several pieces of information: the name of the donut, and the percent remaining. It also contains tools for accessing and manipulating its own data. We can transfer this entire package between methods in Java by simply writing the name of the handle variable to that particular object. Very powerful! A peek at CIT-130: Object-oriented design 1Donut objects could store other objects inside of them. It actually does this by storing a String in the member variable name. This process is called composition. In Java, almost all objects contain many other objects, often nested inside one another. We can create magnificently complex structures this way and pass those huge structures around with a single handle variable!! |
Let NetBeans help you code well
If you typed in our refactored DonutLand_Refactored code exactly like the sample, you may have noticed that NetBeans added yellow squiggly lines underneath the declarations of thenibble and megaByte constants added before the declaration of main. When one hovers over these squiggled identifiers, we get this message:

If we did a little thinking on this, we'd remember that the naming convention is to write names of constants (variables declared with the keyword final) in all caps, so the names should most appropriately have been NIBBLE and MEGA_BITE. Don't forget: NetBeans is on our side! Its so-called error messages can be helpful tips!
arrow_upwardback up
extensionExercise 1: Paper compiling object creation and manipulation
Load the following PDF exercise, print it out, and work each of the four problems by hand. The goal here is to learn how the compiler processes each and every line in our programs. While seemingly tedious, if you can generate the correct output by hand, you'll be a pro at writing bug-free Java code because you can anticipate what the compiler will do with each statement.
Don't check the key until you've given it your best effort!
Paper object compiling student exercise (PDF)
Paper object compiling student exercise (editable .odf)
Answer key to paper object compiling exercise (PDF)
arrow_upwardback up
extensionMini Project: An Edible Object Feast
The mini project for this module asks you to add additional Object blueprints in addition to our Donut class. Study the following specification document closely and code up your work.
program objective |
Create an object-oriented feast by creating two additional "blueprint" classes, such as Salad or Burger. For each of your new food items, include a member variable called percRemaining so that we can track the status of all our edible objects. For each of your "blueprint" classes, add additional member variables to make your objects interesting and useful. For example, if I were creating a Salad object blueprint, I could add the following member variables and methods: |
sample additional food object |
Remember: You've seen demos of Donut and Salad objects, so be creative and come up with new items! ![]() |
requirement 1 |
Create a class that contains a main method (just like DonutLand called FoodLand). In this main method, create an instance of each of your three food objects (Donut included). Systematically write values to each of your object's member variables. In the Salad example, I would create a Salad with new and then set its containsNuts variable, lettuceType, and vegetarian member variables to whatever values seem appropriate to the model. |
requirement 2 |
Call each method you've written on each of your three objects. Write code in main to show that each of your methods works as expected. For example, in our Donut example, we called simulateEating(int percentEaten) and passed in a value of 12 to symbolize eating 12% of the donut. We also printed to the console the value of percEaten before and after the call to simulateEating to show that the method correctly manipulated the member variables on that particular Donut object. |
Submission
Test your code. Comment your code. Proof your code. Then upload all your .java files to GitHub. Make an entry in our tracking spreadsheet to your package that contains each object blueprint and FoodLand.
arrow_upwardback up
extensionModule project extension exercises
Nutrition Facts: Add handy member variables
We could imagine a meal or menu planning application that can provide the user with item-level and summary nutrition information about a selection of food items. Explore these options with your three food objects. Perhaps start simple: add a protein_grams to each of your objects. You can hard-code the correct value for each food item in your blueprint class, i.e. Donut so that when you create an instance of that object with new, the member variable is already loaded up with the correct nutrition information.
Inside FoodLand, write code which tallies up the total grams of protein in several objects. Some sample code to get you started:

arrow_upwardback up