Java nested and inner classes

Nested classes are defined within other classes which are known as outer or enclosing classes. There are two main categories of nested classes.

1- Static nested classes

2- Inner classes (non-static nested classes)

Nested classes are members of their enclosing classes.

One of the practical reason to define inner classes is that they can access all the members of their enclosing classes even if they are private.

Think about it as a method, which has access to all the instance variables of its class even if they are private.

nested-classes-color

What is a nested class?

A nested class is a class defined within other class which we call an enclosing class or an outer class.

Nested classes have a strong relationship with their outer classes. The existence of a nested class depends on the existence of its outer class. An example is a building and its rooms. If a building is demolished, then the rooms don’t exist without it. Technically you can create a nested class object by creating first an object of the outer class.

 

What are the advantages of nested classes?

  1. Since a nested class is only useful for its outer class, it is logical to keep them together.
  2. Creating a room without the building doesn’t make sense. That is why you can’t technically create an object of a nested class without creating its outer class object first.
  3. The nested classes have a direct access to the members of their outer classes even if they are declared private.
  4. This technique helps to organize the code better and make it more maintainable.

 

Outer classes (enclosing classes)

  1. Outer classes can only be declared public or package private.
  2. An outer class has no direct access to the members of its nested class.

Inner classes

  1. Inner classes can be declared private, protected, public and package private.
  2. An inner class has a direct access to the methods and fields of its outer class even if they are declared private.
  3. Instantiating an inner class starts with instantiating its outer class.
  4. An inner class can not define any static members itself, because they are associated with instances of their outer classes.
  5. You can instantiate inner classes using the following statement:

Inner inner = new Outer().new Inner(); 

Static nested classes

  1. Static nested classes can be declared private, protected, public and package private.
  2. You can access static nested classes by using the name of its outer class. Nested nested = new Outer.Nested();
  3.  A static nested class can not refer to its outer class’s instance members directly.
  4. A static nested class can access its outer class’s instance variables through an object.

Outer.nest nest = new Outer.nest();

 

Example

In the example below, the inner class “File” has access to the “folderName” which is declared private within its outer class. It uses the folder name in the method “getFilePath”. The following statement is used to create objects of  the nested class.

File file = new Folder().new File();

When the following program compiled and run, it writes “c:\\downloadFolder\images” to the standard output.

 

public class Folder {

	private String folderName;

	class File {
		String fileName;
		double fileSize;
		public String getFilePath(){
			folderName = "downloadFolder";
			return "c:\\\\" + folderName + "\\images";
		}
	}
	public static void main(String[] args){
		File file = new Folder().new File(); // creating a file object
		System.out.println(file.getFilePath());
	}
}

 

The following will change If the nested class File is declared static in the above example.

  1. You cannot access the variable folderName within the method getFilePath.
  2. You can use the name of the outer class to access the inner class:

Folder.File file = new Folder.File();  or

File file = new Folder.File();

 

The UML diagram represents a composition relationship

In the UML diagram below, the relationship between the class folder and its inner class file is represented as a composition relationship. The reason is that they are closely associated with each other. If you destroy a folder, then all its files will be also destroyed. Other examples is a building and its rooms. If a building is demolish, all its rooms would be also destroyed.

 

There are many examples like that in the real world such as human and his brain or heart. in those examples the composed or nested class can not exist without its composer (outer). The solution that Java offers is creating a nested class within the enclosing class.

In that way the nested class can access the instance variables and methods of its enclosing class.

 

nested_class_composition

 

How to convert the UML diagram into Java code?

Java uses the composition relationship by declaring the composer as enclosing class and the composed class as a nested class.

 

public class Folder {

	private String folderName;

	public String getFolderName(){
		return folderName;
	}
	class File {
		String fileName;
		double fileSize;
		public String getFilePath(){
			fileName = "Images";
			folderName = "Download";
			String path = "c:\\\\" + folderName + "\\" + fileName;
			return path;
		}
	}
	public static void main(String[] args){
		File file = new Folder().new File(); // creating a file object
		System.out.println(file.getFilePath());
	}
}

 

Exercise 1:  Inner Classes

What happens when you try to compile and run the following program?

public class Outer {

	private int x;
	private int y;

	Outer() {
		x = 2;
		new InnerA();
		y = 3;
	}
	class InnerA {
		InnerA() {
			System.out.print("-y" + y + "-x" + x);
		}
	}
	public static void main(String[] args){
		InnerA innerA = new Outer().new InnerA();
	}
}

Select the correct answer.


Exercise 2:  Nested Classes

What happens when you try to compile and run the following program?

public class Outer {

	public int x = 1;
	private int y = 1;

	Outer() {
		x = 2;
		y = 2;
		new InnerA();
	}
	class InnerA {
		InnerA() {
			System.out.print("-y" + y);
			y = 5;
		}
		void methodA(){
			System.out.print("-x" + x);
		}
	}
	public static void main(String[] args){
		InnerA innerA = new Outer().new InnerA();
		innerA.methodA();
	}
}

Select the correct answer.


Please, leave your questions, feedback and suggestions in the comments below!
Sarmaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.

Sar Maroof's new book
Java quizmaster for beginners (English)

Java quizmaster voor beginners (Dutch)
Sar Maroof is the author of two Java books namely, Java quizmaster for beginners and A guide to build a Java application.
Experience with developing web applications since 2001
Sun Certified JSP as well as EJB
CIW Certified Internet Webmaster
Applied Science in Physics HBO Amsterdam
As well as Bachellor Science in Physics.
 Subscribe To sarmaroof RSS Feeds! (Your Browser)
 Mail This Page To A Friend!
 Bookmark This Page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

3 Comments

Add a Comment
  1. My hat is off to your astute command over this toaob-crpvi!

  2. Very helpful, looking forward to seeing more of your articles and quizzes!

    1. Great ariltce, thank you again for writing.

Leave a Reply

Your email address will not be published. Required fields are marked *

Sarmaroof © 2017