Learn

In this exercise, we will be taking a closer look at static nested classes. First, let’s review the definition of static nested classes. Static nested classes are nested classes that only have access to other static members of their enclosing class. Just like in the previous exercise, we may refer to the static nested class as the inner class and the class that it is encapsulated within as the outer class.

In order to declare a static nested class within an outer class you may use the following code as a guide:

class Outer { String outer; static String typeStatic = "static String type"; String typeGeneric = "generic String type"; // Assign values using constructor public Outer(String name) { this.outer = name; } // private method private String getName() { return this.outer; } // static nested class static class Inner { String inner; String outer; void printTypeMethod() { // Can access static member of outer class System.out.println("Type of member = " + typeStatic); } } }

Note we have used the keyword static when declaring the inner class. Within the inner class, we also have a method called printTypeMethod(). This method only prints the typeStatic string because it is also static. If we attempted to print typeGeneric this would have resulted in an error when trying to run the program since typeGeneric is not a static variable.

Instantiating a static nested class is a little simpler than instantiating a non-static nested class: Outer.Inner staticNested = new Outer.Inner(). Unlike a non-static nested class, the nested class does not require us to instantiate an object of the type Outer first.

Here are some important things to remember about static nested classes:

  • Unlike non-static nested classes, static classes cannot access any non-static members of its enclosing class, including private and protected members.
  • To instantiate a static nested class, you are not required to first instantiate its enclosing class.
  • The keyword static in member creation is what differentiates a static member from a non-static member in any Java program.

Instructions

1.

Create a static String object called libLocation, and assign it the value “Midfield St.” in the outer class Lib.

2.

In the inner static class Book, create a new static method called printLibraryLocation. Use System.out.println() in the new function to print the following:

Library location: Midfield St.
3.

Instantiate the static nested class Book in the main method.

4.

In the main method, will call the printLibraryLocation() function.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?