Grouping Helper Classes Inside Other Classes, Explained

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

← Anticipating and Recovering from Runtime Errors GracefullyNext lesson: Inner Classes That Depend on Their Enclosing Object →

Earn 3 college credits for Data Structures and AlgorithmsRecommended for credit by NCCRS · Computer Science 251 · self-paced · one payment, lifetime access

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.

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

How programs store and search dataData Structures and Algorithms teaches how to organize data and measure how fast code runs: arrays, linked lists, stacks, queues, trees, heaps, hash tables, sorting and graphs, all written in Java. It is a core course in computer science and software degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
A static nested class is a class declared inside another class with the word static. It is a member of the outer class, named Outer.Nested from outside, such as Campus.Room, yet it is an ordinary class with its own fields, constructors and methods. It has no hidden link to an outer object, so a Room can be created even when no Campus object exists.
Can a static nested class access private members of its outer class?
Yes. Outer and nested code share private access, so a static nested class may use the outer class's private static members directly by name. Instance fields are different: the nested class has no outer object of its own, so it must read them through an object, as in c.name for a Campus c. The outer class may likewise read the nested class's private fields through a nested object.
Why make a linked list Node a private static nested class?
A Node is used only by its list, so nesting it keeps the helper next to the code that needs it. Marking it private hides it, so no other code can depend on how the list stores its data, and the list stays free to change. Each structure can have its own Node without name clashes, and static means each node stands alone, with no link to a list object.
Why does new Room() fail outside the Campus class?
From another class, Room is not a top-level name, so new Room() fails with cannot find symbol, and the full name Campus.Room must follow new. If static is left out of Room's declaration, Room becomes an inner class tied to a Campus object, and creating it with new Campus.Room from another class then fails because the compiler says an enclosing instance is required.

About the Data Structures and Algorithms course

How many college credits is Data Structures and Algorithms?
Data Structures and Algorithms (Computer Science 251) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Data Structures and Algorithms cost and what is included?
$250, paid once, with lifetime access: all 87 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Data Structures and Algorithms take?
It is self-paced with no deadlines. The 87 lessons total about 15 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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.

Data Structures and Algorithms
3 credits · NCCRS
Enroll →