UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 3.2 Free with a free account
Modeling Real-World Entities as Programmable Objects
Data Structures and Algorithms · Chapter 3: Thinking in ObjectsSection 3.2 · lesson 8 of 8713 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Data Structures and Algorithms.
Lesson complete
Earn the 3 college credits for Data Structures and Algorithms
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: How Child Types Borrow and Extend Behavior from Parent Types →← The Five Pillars of Reusable Software DesignNext lesson: How Child Types Borrow and Extend Behavior from Parent Types →
In this lesson
Write Java classes with fields, constructors, methods and safe encapsulation.
- Write a class with fields, constructors and methods, and create objects with new
- Use this, private fields, getters and validating setters to protect object state
- Explain static members, toString, and the difference between equals and double equals
- Trace how object references are copied, aliased, passed to methods and set to null
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,842 words). Read along, or search it.
Opening Question
Describing a Kind of Thing Once
Real programs rarely deal with bare numbers. They deal with books, students, bank accounts and thermostats: things that have facts attached, and that can do something. A library has thousands of books, and each has its own title and page count. Nobody wants to write the same code a thousand times. So how do you describe a kind of thing once, and then make as many as you need, each with its own facts?
Key Idea
Classes as Blueprints for Objects
Think of an architect's drawing. The drawing isn't a house. But from one drawing, a builder can put up as many houses as the street has room for, each in its own color. Java works the same way. A class is the blueprint: you write it once, and it becomes a new type, like int or String. An object is one actual thing built from it, with its own values. Changing one object never changes another.
Class Members
Fields, Methods and Constructors
A blueprint has three kinds of members. Fields are variables stored in every object: its state. Methods are named blocks of code that work on the object: its behavior. And a constructor runs once, as an object is created, to set up its fields. To model something, ask two questions. What does it know? Those answers become fields. What can it do? Those become methods.
Worked Example
A Complete Book Class
Here's a complete blueprint for a book. The first line names it. Everything inside the braces belongs to it. The fields, title and pages, are declared like ordinary variables, inside the braces but outside every method. Every method and constructor can read and change them. The constructor has exactly the class's name, and no return type, not even void. It exists to give a new object sensible starting values. Is long returns true or false. Print card prints, and returns nothing. Inside them, pages means this object's pages.
Creating Objects
New and the Dot Operator
The word new creates an object and calls a constructor. The dot then reaches inside an object, to use one of its fields or methods. Two books: Dune, six hundred twelve pages, and Poems, ninety-six. Run it. Each prints its own card. Dune is long. Poems isn't. Then the program changes one object's field: second dot pages becomes three hundred fifty, and now Poems is long. The two books are independent. Dune never changed.
Default Values
What New Does Behind the Scenes
One line of new hides three steps. Java reserves memory for the object, and fills every field with a default. Then the constructor runs. Then new hands back a reference to the object. Those defaults mean an object never holds garbage. This gadget's fields are never set. Run it: zero, zero point zero, false, and null, meaning no object at all. That's true for fields only. A local variable inside a method gets no default, and the compiler won't let you read it until you've assigned it.
Default Constructor
Losing the Free Constructor
If a class has no constructor at all, Java quietly supplies one that takes nothing, and leaves every field at its default. But the moment you write any constructor of your own, that free one is gone. Box takes a size now, so new Box with empty parentheses no longer compiles. Constructor Box cannot be applied to given types. Required: int. Found: no arguments.
Common Mistake
Shadowed Fields and the This Keyword
Short parameter names like t and p are easy to misread, so programmers prefer parameters named like the fields. But look what happens when the names match, and nothing else changes. Inside the constructor, the parameter shadows the field. So title equals title assigns the parameter to itself, and the fields are never touched. Run the library again: null, zero pages. The fix is the keyword this. It stands for the object being built or used right now, so this dot title is unmistakably the field, and plain title is the parameter.
Quick Check
A Red Lamp Prints Null
Quick check. A lamp has a color, and watts starting at forty. Its constructor says color equals color, then watts equals sixty. What does the program print for a new red lamp? Pause, and predict. It prints, null sixty. Color equals color assigns the parameter to itself, so the field keeps its default, null. But watts has no parameter of the same name, so plain watts is the field, and it becomes sixty.
Access Modifiers
Private, Package, Public and Protected
So far, any code anywhere can write second dot pages equals three fifty. That's convenient, and dangerous. If an account's balance were a field anyone could reach, a careless line could set it to minus five thousand. The cure is encapsulation: hide the fields, and allow changes only through methods that check each request first. An access modifier says who may use a member. Private means only code inside the same class. No modifier means the same package, a folder of related files. Public means anywhere. And protected comes with inheritance, in the next lesson. A dependable rule: make fields private, and make public only the methods outside code truly needs.
Encapsulation Example
A Bank Account With Private Fields
Here's a bank account, built that way. Its number, owner and balance are private.
Compiler Protection
Blocked Access to a Private Balance
Now outside code tries to touch the balance directly. The compiler catches it, long before the program runs. Balance has private access in bank account. Nothing outside the class can put an account into a state that makes no sense.
Getters and Setters
Controlled Access That Validates Input
With the fields private, outside code needs a controlled way in. A getter returns a field's value. A setter changes it, and is the right place to reject bad input. Set owner refuses a null or blank name. The number never changes, so it's final, assigned once in the constructor, and it has no setter. And balance has no setter at all, because the only legitimate ways to change money are deposit and withdraw. Each checks the request, refuses an invalid amount, and reports whether it worked. This pays off twice. A negative balance can't appear, because no method allows it. And if the balance is later stored as whole cents, only this class changes. Every program calling get balance keeps working.
Static Members
Counting Accounts With a Static Field
Every member so far is an instance member: each object has its own copy of each field. But the bank may want to know how many accounts exist in total, and no single account owns that number. Marking a member static attaches it to the class itself. There's exactly one copy, shared by every object, and it exists before any object is made. Every new account adds one to total accounts. Get total accounts is static too, called on the class's name. You've met this already: main is static, because Java starts your program before any object exists. And this has a second use. The two-argument constructor calls this, with parentheses, to reuse the three-argument one, with a balance of zero. That call must be the first statement.
Static Limits
No Instance Fields in Static Code
The limit on static code follows from that. A static method has no particular object behind it, so it can't use instance fields, and it can't use this. Non-static variable count cannot be referenced from a static context. To use an instance field from static code, first get an object, and reach through it.
Printing Objects
Printing Objects Readably
Every object comes with a few ready-made methods. When you print an object, or join it to text, Java calls its to string method. Without one of your own, you get the type's name, an at sign, and a hexadecimal code. The account supplies its own, so it prints readably. Those digits tell a reader nothing, so any class you plan to print deserves a to string of its own.
Object Equality
Same Object Versus Same Meaning
Here's the account's own version. At override marks it as a replacement for the method Java already provides, so a typo in the name is caught at once. Two different questions hide behind the word equal. Are these two variables referring to the very same object? Two equals signs answer that. Do these two objects represent the same thing? That's the job of equals. The ready-made equals behaves just like two equals signs. So for a bank account, equals is replaced: two accounts are the same account if they have the same number. The parameter is an Object, because the method must accept anything. First, the very same object is equal. Then instanceof checks it really is an account, and it's false for null. Only then is it safe to compare numbers, with equals, since the number is a String. When a class replaces equals, Java also expects a matching hash code. That companion comes in a later lesson.
Worked Example
Three Accounts Put to the Test
This program exercises every idea so far, with three accounts. Asha's has five hundred, Ben's uses the two-argument constructor, and a third account reuses Asha's number. Run it. Withdrawing a thousand is refused: false. Asha's account prints with seven fifty, five hundred plus two fifty. Ben's prints with zero, passed through this. A double equals c is false: two separate objects. But a dot equals c is true: both are account A one oh one. Three accounts were made in total. And the setter rejected the blank name, so the owner is still Asha.
References
Primitive Values Versus Object References
One last idea. A variable of a primitive type, like int, holds the value itself. An object variable holds a reference: a way to find the object, like a street address. So copying a primitive copies the number. Copying an object variable copies the reference, making a second name for the same object. And two equals signs compare values for primitives, but the references for objects.
Aliasing
Two Names for One Account
Y equals x copies the reference, not the account. So depositing fifty through y changes the one account, and x sees it: one fifty, and x double equals y is true. Passing an object to a method copies the reference into the parameter. Bonus deposits ten into the caller's real account. Then it points its parameter at a brand-new account, and deposits into that. Only the local reference moved. Back in main, x shows one sixty.
Quick Check
Pia's and Quin's Balances
Quick check. P is Pia's account, with one hundred. Q is set to p, then q is pointed at a new account for Quin, and fifty is deposited through q. What do p and q's balances print? Pause, and predict. One hundred, and fifty. Q equals p made a second name for Pia's account, but the next line moved only q's reference, to Quin's new account. So the deposit went to Quin's account. Pia's account was never touched again.
Null References
Guarding Against Null Pointer Exceptions
The special value null means a variable refers to no object at all. Testing it with two equals signs is correct and safe: true. But calling a method through a null variable has nothing to run on, so the program stops with a null pointer exception. Guard such calls with, if z is not null, whenever a variable might be empty.
Key Takeaways
Classes, Encapsulation and References
To summarize. A class describes a kind of thing with fields, methods and constructors, and new builds one object from it. Encapsulation means private fields, behind public methods that validate input. And this means the current object. Static members belong to the class, and exist once. Override to string to print readably, and equals to compare by meaning. And an object variable holds a reference: assigning it copies the reference, and null means no object.
About Data Structures and Algorithms at UPI Study
Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms
Why take it here
Why students take Data Structures and Algorithms with UPI Study
Where the credit goes
Universities that work with NCCRS
Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Modeling Real-World Entities as Programmable Objects
What is the difference between a class and an object in Java?
What does the this keyword do in a Java constructor?
What is the difference between == and equals in Java?
What happens when you assign one object variable to another in Java?
About the Data Structures and Algorithms course
How many college credits is Data Structures and Algorithms?
How much does Data Structures and Algorithms cost and what is included?
Which universities accept UPI Study credits?
How long does Data Structures and Algorithms take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Data Structures and Algorithms.
87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →