Java beágyazott és belső osztály (példákkal)

Ebben az oktatóanyagban példák segítségével megismerheti a Java beágyazott osztályát és típusait.

A Java-ban meghatározhat egy osztályt egy másik osztályon belül. Az ilyen osztály ismert nested class. Például,

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

Kétféle beágyazott osztály hozható létre a Java-ban.

  • Nem statikus beágyazott osztály (belső osztály)
  • Statikus beágyazott osztály

Ajánlott olvasmány :

  • Java Access Modifiers
  • Java statikus kulcsszó

Először nézzük meg a nem statikus beágyazott osztályokat.

Nem statikus beágyazott osztály (belső osztály)

A nem statikus beágyazott osztály egy másik osztályon belüli osztály. Hozzáférhet a befogadó osztály (külső osztály) tagjaihoz. Közismert nevén inner class.

Mivel inner classlétezik a külső osztályon belül, először a külső osztályt kell példányosítania a belső osztály megjelenítéséhez.

Íme egy példa arra, hogyan lehet deklarálni a belső osztályokat Java-ban.

1. példa: Belső osztály

 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()); ) )

Kimenet :

 Processzor gyorsítótár = 4,3 RAM óra sebesség = 5,5

A fenti programban két beágyazott osztály létezik: Processzor és RAM a külső osztályon belül: CPU. A belső osztályt védetté nyilváníthatjuk. Ezért a RAM osztályt védettnek nyilvánítottuk.

A főosztályon belül,

  • először egy külső osztályú CPU példányát hoztuk létre.
  • A külső osztály példányát felhasználva létrehoztuk a belső osztályok objektumait:
     CPU.Processor processor = cpu.new Processor; CPU.RAM ram = cpu.new RAM();

Megjegyzés : A dot ( .) operátorral létrehozzuk a belső osztály egy példányát a külső osztály felhasználásával.

Hozzáférés a külső osztály tagjaihoz a belső osztályon belül

Ennek a kulcsszónak a segítségével érhetjük el a külső osztály tagjait. Ha szeretne többet megtudni erről a kulcsszóról, keresse fel a Java-t.

2. példa: Hozzáférés a tagokhoz

 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()); ) )

Kimenet :

 Motor típus 8WD esetén = nagyobb motor típus 4WD esetén = kisebb

A fenti programban a motor nevű belső osztály van a külső osztályú autó belsejében. Itt vegye észre a sort,

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

Mi használ thiskulcsszó eléréséhez carType változó külső osztályban. Lehet, hogy észrevette, hogy a használat helyett this.carTypemi használtuk Car.this.carType.

Ugyanis, ha nem említettük a külső osztály autó nevét, akkor a thiskulcsszó képviseli a tagot a belső osztályon belül.

Hasonlóképpen a külső osztály módszeréhez is hozzáférünk a belső osztálytól.

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

Fontos megjegyezni, hogy bár getCarName()ez a privatemódszer, a belső osztályból képesek vagyunk hozzáférni hozzá.

Statikus beágyazott osztály

A Java-ban staticosztályt definiálhatunk egy másik osztályon belül is. Az ilyen osztály ismert static nested class. A statikus beágyazott osztályokat nem nevezzük statikus belső osztályoknak.

A belső osztálytól eltérően a statikusan beágyazott osztály nem fér hozzá a külső osztály tagváltozóihoz. Ez azért van, mert a statikusan beágyazott osztály nem igényli a külső osztály példányának létrehozását.

 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.
  • A nem statikus beágyazott osztályok (belső osztályok) hozzáférhetnek a külső / bezáró osztály többi tagjához, még akkor is, ha magánként nyilvánítják őket.

érdekes cikkek...