Nested and inner classes


Monday, December 4, 2023

Nested and Inner Classes in Java are defined within another class and have access to the members of the containing class, including private members.

There are two main types of nested classes in Java: static inner classes and non-static inner classes.

Inner Classes (Non-Static)

Non-static inner classes are those defined within another class without the static keyword. They have access to all members of the containing class, including private members. Additionally, they have implicit access to the instance of the containing class.

public class OuterClass {
    
    private int externalData = 10;

    // Non-static inner class
    public class InnerClass {
        public void showExternalData() {
            System.out.println("External data from inner class: " + externalData);
        }
    }
    
    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        OuterClass.InnerClass inner = outer.new InnerClass();
        inner.showExternalData();
    }
}

In this example, the class OuterClass has an attribute named externalData initialized with the value 10. It contains a non-static inner class called InnerClass. The inner class has a public method named showExternalData(), which prints the value of externalData from the inner class.

The non-static inner class InnerClass has access to all members of the outer class, including the private member externalData. It contains a method showExternalData() that prints the value of externalData from the inner class.

In the main method, an instance of the outer class (OuterClass) is created called outer. Then, an instance of the inner class (InnerClass) is created using the syntax outer.new InnerClass(). Finally, the method showExternalData() is called from the instance of the inner class, printing the value of externalData from the inner class.

Static Inner Classes

Static inner classes are similar to non-static ones but are defined with the static keyword. Unlike non-static classes, they do not have access to the members of the containing class without an instance of it.

public class OuterClass {

    private static int staticData = 20;

    // Static inner class
    public static class StaticInnerClass {
        public void showStaticData() {
            System.out.println("Static data from static inner class: " + staticData);
        }
    }

    public static void main(String[] args) {
        OuterClass.StaticInnerClass staticInner = new OuterClass.StaticInnerClass();
        staticInner.showStaticData();
    }
}

The class OuterClass has a static member named staticData initialized with the value 20. It contains a static inner class named StaticInnerClass.

The static inner class StaticInnerClass does not have access to non-static members of the outer class. However, it can access static members. It contains a public method named showStaticData() that prints the value of staticData from the static inner class.

In the main method, an instance of the static inner class (StaticInnerClass) is created using the syntax OuterClass.StaticInnerClass. Then, the method showStaticData() is called from the instance of the static inner class, printing the value of staticData from the static inner class.

Share it

Share it on your social media and challenge your friends to solve programming problems. Together, we can learn and grow.

Copied

The code has been successfully copied to the clipboard.

More Exercises

Continue improving your Java programming skills with our selection of practical exercises from the lesson. Click on Practice and challenge your knowledge!

1

Classes and objects

Delve into the basics of object-oriented programming in Java. Learn about classes and objects, the essential components that breathe life into modularity and code reusability in this versatile programming language.

2

Attributes and Methods

Dive into the essence of object-oriented programming in Java by gaining a deep understanding of attributes and methods. Explore how these fundamental elements are crucial for creating classes and objects, providing modularity and efficiency in software development.

3

Constructors

Discover the importance of constructors in Java and how they crucially initialize objects. Learn best practices to ensure consistency in instance creation and optimize your code with our detailed examples.

4

Access Modifiers

5

Getters and Setters Methods

Learn how to create secure interfaces with getters and setters methods in Java. Explore how these methods promote encapsulation and provide precise control over attribute modification.

6

Person class and method ToString()

Create a Java program that requests three names of people from the user and stores them in an array of objects of type Person.

7

Constructors and destructors

Create a Java program that prompts the user for three names of people and stores them in an array of Person-type objects.

8

instanceof operator

The instanceof operator in Java is used to check if an object is an instance of a specific class, subclass, or implements a specific interface.

9

Class person, student and teacher

Create a new Java project with three classes plus another class to test the logic of the code. The main classes of the program are the following.

10

Nested and inner classes

Nested and Inner Classes in Java are defined within another class and have access to the members of the containing class, including private members.

11

Inheritance

Inheritance in Java is one of the fundamental pillars of Object-Oriented Programming (OOP). It provides a mechanism through which a class can inherit properties and behaviors from another class.

12

Photo book class

Create a Java program to manage a photo book using object-oriented programming.

13

Creating Classes and Objects

Create a class called 'Person' with attributes like name, age, and address. Then, create objects of the 'Person' class and initialize their attributes. Implement methods to display and modify these attributes.

14

Inheritance of objects

Create a Java program that prompts the user for three names of people and stores them in an array of Person-type objects.

15

Abstract classes

An abstract class is a class that cannot be instantiated directly. This means you cannot create objects directly from an abstract class using the new operator.

16

Shapes - Class diagram

Create a Java program that represents the following UML class diagram.

17

Interfaces

Create a Java program that implements an IVehiculo interface with two methods, one for Drive of type void and another for Refuel of type bool that has a parameter of type integer with the amount of gasoline to refuel.

18

Abstract classes

Create a Java program that implements an abstract class Animal that has a Name property of type text and three methods SetName (string name), GetName and Eat.

Object-oriented programming

Practice object-oriented programming exercises in Java. Learn to use constructors, destructors, inheritance, interfaces among others.

Fundamentals concepts
Practice exercises

Keep learning

C# Programming Course

Free programming course with practical exercises and solutions in C#. Start learning right now!

Exercises C# App

Take your Exercises C# lessons everywhere with our Android app. Download it now from Google Play