UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 4.4 Free with a free account
Grouping Helper Classes Inside Other Classes
Data Structures and Algorithms · Chapter 4: Abstract Types, Exceptions, and Nested ClassesSection 4.4 · lesson 14 of 878 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: Inner Classes That Depend on Their Enclosing Object →← Anticipating and Recovering from Runtime Errors GracefullyNext lesson: Inner Classes That Depend on Their Enclosing Object →
In this lesson
Use static nested classes to keep helper types close and private.
- Declare a static nested class and refer to it by its full Outer.Nested name
- Explain what a static nested class may access in its enclosing class
- Choose the right access modifier for a nested helper such as a Node
- Decide where a helper class belongs based on who uses it
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,168 words). Read along, or search it.
Opening Question
Where Should a Helper Class Live
Some types exist only to serve one other type. A linked structure needs tiny nodes that nobody outside it will ever use. A campus program needs rooms that only make sense inside a campus. Give each helper its own public file, and the project gets cluttered. Worse, other code starts to depend on a detail that should stay private. So where should a helper like that live?
Definition
Declaring a Static Nested Class
Java lets you write a class inside another class. Add the word static, and it's a static nested class. Here, Room is written inside Campus. Three facts about it. First, it's a member of Campus, just like a field or a method. From outside, its full name is Campus dot Room. Second, it's still an ordinary class, with its own fields, constructor and methods. It can even have static members of its own. Third, it gets its own compiled file. Compile Campus, and list the folder. The nested class's file joins the two names with a dollar sign.
Access Modifiers
Private, Package and Public Nested Classes
Because it's a member, a nested class can carry any access modifier a field can. A top-level class can only be public, or have none. Private means only code inside the enclosing class may use it: a helper nobody else should know about. No modifier means code in the same package, a folder of related files, may use it too. Public means any code, written as Campus dot Room. Protected works with inheritance, and isn't needed here.
Key Rule
No Hidden Link to an Outer Object
The word static carries one promise: there's no hidden link to an outer object. A Room can exist when no Campus object exists at all. That decides what Room may use directly. A static member of Campus, even a private one, is fine. The constructor bumps roomCount by name. But name is different. It exists once per Campus object, so Room reads it through a Campus that's handed in: c dot name. Try reading name directly, with no Campus object, and Java refuses. A Room has no particular campus to ask. The cure is the one in the listing: pass a Campus in, and read the field through it.
Quick Check
Which Line Cannot Read City
Quick check, with a new class. Library has a private static loans count, and a private city field. Card is a static nested class with two methods. One bumps loans, and one returns city. Which line won't compile? Pause, and decide. It's return city. city belongs to each Library object, and a static nested Card has no particular library to read it from. loans is fine, because it's static: there's one shared copy, private or not, and Card may use it by name.
Motivation
Four Reasons to Nest a Node
Now take a node: a tiny object holding one value, and a reference to the next node. Structures built from nodes appear all through this course. Where should Node live? A helper that only one type uses has four good reasons to live inside it. It belongs together: anyone reading the chain finds its helper right there. And marked private, it can be hidden, so nobody can depend on it. There are no name clashes: many types can each have a Node, because each is really Chain dot Node, or Tree dot Node. And marked static, each node stands alone, with no connection to any chain object.
Worked Example
A Chain With a Private Node
Here's Chain, with a private static nested Node. Inside Chain, the short name Node works. demo makes three nodes, and links them by hand. Real lists that add, search and remove nodes come in chapter six. Run it, and it prints 7, 8, 9, joined by arrows. Notice that Chain reads a dot value and a dot next, although both fields are private in Node. Outer and nested code share private access.
Encapsulation
Outside Code Cannot Reach Chain's Node
Now see what private on the helper buys. Code in a different file tries to make a Chain dot Node. The compiler stops it twice, once for the type and once for the constructor: Node has private access in Chain. So no other part of the program can come to depend on how Chain stores its data. Chain is free to change it later.
Shared Access
Private Access Across Nesting
Normally, private means this class only. Nesting widens that: a private member belongs to the whole outermost class, nested parts included. So Room may use Campus's private static count directly, and its private name through a Campus object. And Campus may read Room's private number, through a Room object, as peek does. Any other code is refused. The rule is about permission, not about having an object. Even allowed, Room still needs a Campus to read a name from.
Creating Objects
Rooms Before Any Campus Exists
With no hidden link, creating a nested object is simple. From another class, write the full name: new Campus dot Room. Two rooms are made before any Campus exists. A Campus called North comes afterward, only because label needs one. Run it. North dash 101: label read the name from the Campus passed in, and the number from its own room. Then 2: each Room constructor added one to the single shared count. And 102: peek read r2's private number.
Common Mistakes
Short Names and Missing Static
Two slips to avoid. First, the short name from outside. Room isn't a top-level name, so new Room fails with cannot find symbol. Second, leaving out static. Then Room is tied to a Campus object, and new Campus dot Room, from another class, fails too. The compiler says an enclosing instance is required: it looks for an outer object that isn't there. Classes tied to an outer object get a lesson of their own.
Quick Check
Declaring a Graph's Edge Type
Quick check, with a new design. A Graph class has a public method, edges, that hands its Edge objects to any caller who asks. Edge objects never need a Graph object. How should Edge be declared? Pause, and decide. Public static. Outside code receives edges as part of what Graph offers, so callers must be able to name the type, as Graph dot Edge. Private would hide the very type that edges hands out. And no modifier limits it to Graph's own package, but any caller may ask.
Decision Guide
Where a Helper Belongs
So here's where a helper belongs. If only the enclosing class uses it, and it needs no outer object, make it a private static nested class. If other types in the package use it too, give it its own top-level file, or nest it with no modifier. If outside code creates or receives it as part of the offering, make it public static, used as Outer dot Helper. And if each helper must know which outer object made it, that's an inner class, which gets a lesson of its own.
Key Takeaways
Static Nested Classes in Summary
To sum up. A static nested class is declared inside another class with static, and named Outer dot Nested from outside. It has no hidden link to an outer object, so its objects are created without one. Nest a helper like Node when only one class uses it: it stays close, it can be private, and its name can't clash. Outer and nested code share private access. Outer static members are used directly, and instance members only through an 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 Grouping Helper Classes Inside Other Classes
What is a static nested class in Java?
Can a static nested class access private members of its outer class?
Why make a linked list Node a private static nested class?
Why does new Room() fail outside the Campus class?
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 →