UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 4.5 Free with a free account
Inner Classes That Depend on Their Enclosing Object
Data Structures and Algorithms · Chapter 4: Abstract Types, Exceptions, and Nested ClassesSection 4.5 · lesson 15 of 8711 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 Arrays Store Data →← Grouping Helper Classes Inside Other ClassesNext lesson: How Arrays Store Data →
In this lesson
Use inner, local and anonymous classes tied to an outer object.
- Explain how an inner object stays linked to the outer object that created it
- Create inner objects with outer.new and use Outer.this when names clash
- Write local and anonymous classes that follow the effectively final rule
- Decide between a static nested class and an inner class
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,683 words). Read along, or search it.
Opening Question
A Jersey That Belongs to One Team
Picture a sports jersey with the number 7. It only means something as part of one team: it shows that team's name, and it's on that team's roster. Some things in a program are like that. They make sense only as part of one particular object, and they keep needing that object's private details. Java lets you write such a type right inside the type it depends on. How does it stay tied to one object? And when is that the right choice?
Definition
Inner Classes Linked to an Outer Object
Here's a team, and the players who belong to it. Player is a class written inside Team, without the word static. That makes it an inner class. Team is called the outer class. And here's the key fact: every inner object is built from an existing outer object, and stays linked to it. Because of that link, a player may read, and even change, its team's private fields, with no special permission. Look at label. It uses Team dot this dot name: the private name field of the player's team, which is a different object.
Demo
Players Signed to Reds and Blues
A short program builds two teams, Reds and Blues, and signs one player to each. Ana is signed through reds dot signPlayer. Ben is created with blues dot new Player. Both forms tie the new player to one team. Compile both files, and run it. Each player reports its own team: Ana of the Reds, and Ben of the Blues. Nothing in the source mentions it, but each Player object holds a hidden reference to the Team that created it.
Under the Hood
Inspecting the Hidden Link With Javap
That hidden link is real. javap, the JDK's class inspector, lists the members of a compiled class. The inner class compiles to a file named Team, dollar sign, Player. Quote that name, or the shell reads the dollar sign as a variable, and shows you Team instead. There's an extra field, this dollar zero. That's the link. And the constructor quietly takes a Team as its first argument. So with no Team to pass in, no Player can be built.
Creating Objects
Where New Is Written Matters
Since an inner object needs an outer one, the way you create it depends on where the word new is written. Inside an instance method of Team, a plain new Player uses the current team, filled in automatically. That's what signPlayer does. Anywhere else, write the team first: blues dot new Player. The object before the dot becomes the player's team. And with no outer object at all, as in new Team dot Player, the compiler refuses.
Common Mistake
An Enclosing Instance Is Required
That last row is the most common beginner slip. Here, main tries it in one line. The compiler says an enclosing instance that contains Team dot Player is required. Enclosing instance is the formal name for the outer object. A related slip. A class named Shop has an inner class, Item, and Shop's own main method writes new Item. But a static method has no current object, so there's no this to supply as the outer object. The message is about this. The fix is to make a Shop first, and write shop dot new Item. Or create the item from an instance method, the way signPlayer does.
Name Clashes
Reaching the Outer Field When Names Clash
Back inside Player, two objects are in play: the player itself, and the team behind the link. And both have a field called name. When names collide, Java picks the nearest one. So a plain name means the player's own field, and so does this dot name. To reach the team's field, write the outer class's name, a dot, and this. For Ana, Team dot this dot name gives Reds. If the names didn't clash, the outer field's name alone would reach it. But writing Team dot this is often clearer for a reader.
Quick Check
A Bank Account Tag Without a Clash
Quick check, with a new class. A bank has a private name field, and an inner Account class with an id field, and nothing else. Account's tag method returns name, then the id. What does this program print? Pause and predict. It prints Union, number 4. Account has no field called name, so there's no clash, and the plain name reaches the bank's field through the hidden link. There's no compile error, because the outer field is in scope. And it isn't null, because acct was built from a bank whose name is Union.
Local Classes
A Greeter Declared Inside a Method
A nested class doesn't have to sit beside the fields. A local class is declared inside a method body, the way a local variable is. Here, greetAll declares a class named Greeter. That name works only in the rest of this method. Nothing outside can even see it. Greeter uses prefix, a parameter of the surrounding method. Run it, and both people are welcomed. That's allowed, with one rule. A local class may use a local variable of its method, but only if that variable never changes after it's set. Java calls that effectively final. The class keeps its own copy of the value, and a later change would leave the copy out of date.
Compile Error
Effectively Final Local Variables
Break the rule, and the compiler says so. Here, count starts at 0, the local class prints it, and then count is set to 5. The message: local variables referenced from an inner class must be final, or effectively final. To fix it, remove the later assignment, or copy the final value into a new variable that's set only once.
Anonymous Classes
One Object of a Nameless Class
An anonymous class goes one step further: it has no name at all. Its contract here is a one-method interface, Greeting, whose text method returns a string. Write new, the contract's name, parentheses, then a body in braces. That makes one object, of a class that never gets a name. The first one is stored in g, and it uses city, which obeys the same effectively final rule. The second is created, and handed straight to show, without ever being named. Note the semicolon after the first body's closing brace: it's all one statement. Run it: Hello from Lima, then Goodbye. Anonymous classes suit short, one-time jobs. Once a body grows past a few lines, a named class reads better.
Overview
Four Kinds of Nested Class
So there are four kinds of nested class. A member inner class sits beside the fields, and helps many methods. A local class lives inside one method. An anonymous class sits right at the point of use, as one object. Both of those reach the outer object, when their method isn't static. And a static nested class, from the last lesson, has no outer object at all.
Quick Check
A Loop Counter in an Anonymous Class
Quick check. This loop counts i from one to three. On each pass, it makes an anonymous Greeting, whose text is Tag, plus i. What happens when you compile and run it? Pause and predict. It fails to compile. The loop's i plus plus changes i on every pass, so i isn't effectively final, and the anonymous class may not use it. The fix: copy i into a fresh variable, n, inside the loop. Each n is set once, so it's effectively final. Now it prints Tag 1, Tag 2, and Tag 3.
Classic Use
A Cursor That Reads Live List Data
Inner classes have a classic use. To iterate means to visit a collection's items one after another, and the helper that remembers its place is a cursor. A cursor needs the collection's private data. It makes no sense without that collection. And one collection may have several cursors at once. Here's a list of names with an inner Cursor class. The cursor keeps one value of its own: its position. It reads items and size straight from the list, with no getter methods. The array stays private, but the list's own cursor can reach it. This program fills the list with Ana, Ben and Cy, and then makes two cursors on it. The first cursor moves twice, and prints Ana and Ben. The second, made from the same list, starts at the beginning on its own, and prints Ana. Then Dee is added, after both cursors exist. The first cursor still finds Dee, because it reads the list's live data through its link, not a copy. Had Cursor been a separate class, the list would have to hand over its array, or add getters, which weakens the privacy of its data.
Comparison
Static Nested Versus Inner
Last, the choice. A static nested class and an inner class differ by one word in the heading, but they behave very differently. A static nested class is just grouped with its outer class. It has no hidden link, so a plain new Label works, even inside main. An inner class is tied to one outer object. Peek reads size from one particular box, so it's made with box dot new Peek. Run it, and it prints: A box doubled: 6. But if a static nested class tries to read the box's size, the compiler stops it. It has no box to read size from.
Rule of Thumb
Make It Static Unless Data Is Needed
Here's the rule of thumb. If the nested class never uses the outer object's instance data, make it static. An inner object holds a reference to its outer object. As long as the inner object is in use, the outer object can't be cleared from memory. So a needless link costs a little memory, and forces every creator to supply an outer object. When the data is needed, an inner class is exactly right. And a helper needed in only one method can live there, as a local class, or as a short anonymous one.
Key Takeaways
Inner, Local and Anonymous Classes
To sum up. An inner class is a non-static class inside another, and every inner object is linked to one outer object, so it can use that object's private data. From outside, create one with outer dot new. And Outer dot this names the enclosing object, when names clash. Local and anonymous classes live inside one method, and may use only effectively final local variables. Choose static nested when the outer object's data isn't needed, and inner when it is.
Think About It
A Key-Value Helper for a Table
Something to think about. A lookup table needs a small helper type that holds one key and one value, and never reads any field of the table. Should that helper be an inner class, or a static nested class? And what would the wrong choice cost?
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 Inner Classes That Depend on Their Enclosing Object
What is the difference between an inner class and a static nested class in Java?
How do you create an inner class object from outside the outer class?
What does effectively final mean in Java?
What is an anonymous class 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 →