Nesting classes in java

Tutorial Nesting Classes in Java

All the classes we studied earlier were stored inside their own file, and the name of this file was always the same as the class name.

In the Java programming language, we can create another class within a class and store them together. These classes are called nested classes. A class that contains another class is called the top-level class. In the Java programming language, there are four types of nesting classes that are:

  • Static member classes:
    A static member class has access to all of the static class-leading methods (high-level class).
  • Non-static member classes:
    These classes are usually referred to as “internal” classes. These classes require sampling. This type of class has access to all main class data and methods (top level).
  • Local
    Classes: These classes are limited to a block of codes.
  • Anonymous
    Classes: These types of classes are local classes that do not have an identifier (name).

 


The main reason for putting a class inside another class is that the inner class is only used by the original class (upper level). In other words, the internal class is an auxiliary class for the original class. Putting classes inside each other makes them easier to understand, and keeping codes even easier.

For example, suppose we have created a class called real estate listing for an estate consultant to provide real estate property information. This class can contain props such as listing number and price, and the address and the neighborhood where the house is located. But as another way, we can define the price and listing number props in the main class, and define the street address and squareFeetproperty within the inside of the HouseData class. This is illustrated in Figure 4.39:

 

Note that the inner class of image 4.39 is a private class.

You do not have to define internal classes privately. But if you do this, its content will not be visible or accessible to external classes. If you want the content of a class to be available for external classes, you can not define it internally. An internal class can access the protocols and the original class (top level) methods, even if they are private. Main classes (upper level) can also have access to the contents of the inner class.

If you do not want to create your classes, you can combine an ordinary class with another with composition. (The composition topic is explained in the previous article

Leave a Comment

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

Scroll to Top