Classe Java Nested e Inner (com exemplos)

Neste tutorial, você aprenderá sobre a classe aninhada em Java e seus tipos com a ajuda de exemplos.

Em Java, você pode definir uma classe dentro de outra classe. Essa classe é conhecida como nested class. Por exemplo,

 class OuterClass ( //… class NestedClass ( //… ) )

Existem dois tipos de classes aninhadas que você pode criar em Java.

  • Classe aninhada não estática (classe interna)
  • Classe aninhada estática

Leitura recomendada :

  • Modificadores de acesso Java
  • Java Static Keyword

Vejamos primeiro as classes aninhadas não estáticas.

Classe aninhada não estática (classe interna)

Uma classe aninhada não estática é uma classe dentro de outra classe. Ele tem acesso aos membros da classe envolvente (classe externa). É comumente conhecido como inner class.

Como inner classexiste dentro da classe externa, você deve instanciar a classe externa primeiro, para instanciar a classe interna.

Aqui está um exemplo de como você pode declarar classes internas em Java.

Exemplo 1: classe interna

 class CPU ( double price; // nested class class Processor( // members of nested class double cores; String manufacturer; double getCache()( return 4.3; ) ) // nested protected class protected class RAM( // members of protected nested class double memory; String manufacturer; double getClockSpeed()( return 5.5; ) ) ) public class Main ( public static void main(String() args) ( // create object of Outer class CPU CPU cpu = new CPU(); // create an object of inner class Processor using outer class CPU.Processor processor = cpu.new Processor(); // create an object of inner class RAM using outer class CPU CPU.RAM ram = cpu.new RAM(); System.out.println("Processor Cache = " + processor.getCache()); System.out.println("Ram Clock speed = " + ram.getClockSpeed()); ) )

Produto :

 Cache do processador = 4,3 Ram Clock speed = 5,5

No programa acima, existem duas classes aninhadas: Processador e RAM dentro da classe externa: CPU. Podemos declarar a classe interna como protegida. Portanto, declaramos a classe RAM como protegida.

Dentro da classe principal,

  • primeiro criamos uma instância de uma CPU de classe externa chamada cpu.
  • Usando a instância da classe externa, criamos objetos de classes internas:
     CPU.Processor processor = cpu.new Processor; CPU.RAM ram = cpu.new RAM();

Observação : usamos o .operador dot ( ) para criar uma instância da classe interna usando a classe externa.

Acessando Membros da Classe Externa dentro da Classe Interna

Podemos acessar os membros da classe externa usando esta palavra-chave. Se você quiser saber mais sobre esta palavra-chave, visite Java esta palavra-chave.

Exemplo 2: acessando membros

 class Car ( String carName; String carType; // assign values using constructor public Car(String name, String type) ( this.carName = name; this.carType = type; ) // private method private String getCarName() ( return this.carName; ) // inner class class Engine ( String engineType; void setEngine() ( // Accessing the carType property of Car if(Car.this.carType.equals("4WD"))( // Invoking method getCarName() of Car if(Car.this.getCarName().equals("Crysler")) ( this.engineType = "Smaller"; ) else ( this.engineType = "Bigger"; ) )else( this.engineType = "Bigger"; ) ) String getEngineType()( return this.engineType; ) ) ) public class Main ( public static void main(String() args) ( // create an object of the outer class Car Car car1 = new Car("Mazda", "8WD"); // create an object of inner class using the outer class Car.Engine engine = car1.new Engine(); engine.setEngine(); System.out.println("Engine Type for 8WD= " + engine.getEngineType()); Car car2 = new Car("Crysler", "4WD"); Car.Engine c2engine = car2.new Engine(); c2engine.setEngine(); System.out.println("Engine Type for 4WD = " + c2engine.getEngineType()); ) )

Produto :

 Tipo de motor para 8WD = Tipo de motor maior para 4WD = menor

No programa acima, temos a classe interna chamada Engine dentro da classe externa Car. Aqui, observe a linha,

 if(Car.this.carType.equals("4WD")) (… )

Estamos usando a thispalavra-chave para acessar a variável carType da classe externa. Você deve ter notado que em vez de usar this.carType, usamos Car.this.carType.

É porque se não tivéssemos mencionado o nome da classe externa Car, a thispalavra - chave representaria o membro dentro da classe interna.

Da mesma forma, também estamos acessando o método da classe externa da classe interna.

 if (Car.this.getCarName().equals("Crysler") (… )

É importante notar que, embora getCarName()seja um privatemétodo, podemos acessá-lo a partir da classe interna.

Classe Aninhada Estática

Em Java, também podemos definir uma staticclasse dentro de outra classe. Essa classe é conhecida como static nested class. As classes aninhadas estáticas não são chamadas de classes internas estáticas.

Ao contrário da classe interna, uma classe aninhada estática não pode acessar as variáveis ​​de membro da classe externa. É porque a classe aninhada estática não exige que você crie uma instância da classe externa.

 OuterClass.NestedClass obj = new OuterClass.NestedClass();

Here, we are creating an object of the static nested class by simply using the class name of the outer class. Hence, the outer class cannot be referenced using OuterClass.this.

Example 3: Static Inner Class

 class MotherBoard ( // static nested class static class USB( int usb2 = 2; int usb3 = 1; int getTotalPorts()( return usb2 + usb3; ) ) ) public class Main ( public static void main(String() args) ( // create an object of the static nested class // using the name of the outer class MotherBoard.USB usb = new MotherBoard.USB(); System.out.println("Total Ports = " + usb.getTotalPorts()); ) )

Output:

 Total Ports = 3

In the above program, we have created a static class named USB inside the class MotherBoard. Notice the line,

 MotherBoard.USB usb = new MotherBoard.USB();

Here, we are creating an object of USB using the name of the outer class.

Now, let's see what would happen if you try to access the members of the outer class:

Example 4: Accessing members of Outer class inside Static Inner Class

 class MotherBoard ( String model; public MotherBoard(String model) ( this.model = model; ) // static nested class static class USB( int usb2 = 2; int usb3 = 1; int getTotalPorts()( // accessing the variable model of the outer classs if(MotherBoard.this.model.equals("MSI")) ( return 4; ) else ( return usb2 + usb3; ) ) ) ) public class Main ( public static void main(String() args) ( // create an object of the static nested class MotherBoard.USB usb = new MotherBoard.USB(); System.out.println("Total Ports = " + usb.getTotalPorts()); ) )

When we try to run the program, we will get an error:

 error: non-static variable this cannot be referenced from a static context

This is because we are not using the object of the outer class to create an object of the inner class. Hence, there is no reference to the outer class Motherboard stored in Motherboard.this.

Key Points to Remember

  • Java treats the inner class as a regular member of a class. They are just like methods and variables declared inside a class.
  • Since inner classes are members of the outer class, you can apply any access modifiers like private, protected to your inner class which is not possible in normal classes.
  • Since the nested class is a member of its enclosing outer class, you can use the dot (.) notation to access the nested class and its members.
  • Using the nested class will make your code more readable and provide better encapsulation.
  • Classes aninhadas não estáticas (classes internas) têm acesso a outros membros da classe externa / envolvente, mesmo se forem declaradas privadas.

Artigos interessantes...