Vnorená a vnútorná trieda Java (s príkladmi)

V tomto výučbe sa pomocou príkladov dozviete o vnorenej triede v prostredí Java a jej typoch.

V prostredí Java môžete definovať triedu v rámci inej triedy. Takáto trieda je známa ako nested class. Napríklad,

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

V Jave môžete vytvoriť dva typy vnorených tried.

  • Nestatická vnorená trieda (vnútorná trieda)
  • Statická vnorená trieda

Odporúčané čítanie :

  • Modifikátory prístupu Java
  • Statické kľúčové slovo Java

Najprv sa pozrime na nestatické vnorené triedy.

Nestatická vnorená trieda (vnútorná trieda)

Nestatická vnorená trieda je trieda v inej triede. Má prístup k členom uzatvárajúcej triedy (vonkajšej triedy). Je všeobecne známy ako inner class.

Pretože inner classexistuje vo vonkajšej triede, musíte najskôr vytvoriť inštanciu vonkajšej triedy, aby sa vytvorila inštancia vnútornej triedy.

Tu je príklad toho, ako môžete deklarovať vnútorné triedy v jazyku Java.

Príklad 1: Vnútorná trieda

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

Výstup :

 Vyrovnávacia pamäť procesora = 4,3 Rýchlosť taktu = 5,5

Vo vyššie uvedenom programe sú dve vnorené triedy: Procesor a RAM vo vonkajšej triede: CPU. Vnútornú triedu môžeme vyhlásiť za chránenú. Preto sme vyhlásili triedu RAM za chránenú.

Vo vnútri hlavnej triedy

  • najskôr sme vytvorili inštanciu procesora vonkajšej triedy s názvom cpu.
  • Pomocou inštancie vonkajšej triedy sme potom vytvorili objekty vnútorných tried:
     CPU.Processor processor = cpu.new Processor; CPU.RAM ram = cpu.new RAM();

Poznámka : .Operátor dot ( ) používame na vytvorenie inštancie vnútornej triedy pomocou vonkajšej triedy.

Prístup k členom vonkajšej triedy v rámci vnútornej triedy

Pomocou tohto kľúčového slova môžeme získať prístup k členom vonkajšej triedy. Ak sa chcete dozvedieť viac o tomto kľúčovom slove, navštívte Java toto kľúčové slovo.

Príklad 2: Prístup k členom

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

Výstup :

 Typ motora pre 8WD = väčší typ motora pre 4WD = menší

Vo vyššie uvedenom programe máme vnútornú triedu s názvom Engine vo vonkajšej triede Car. Tu si všimnite riadok,

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

Na thisprístup k premennej carType vonkajšej triedy používame kľúčové slovo. Možno ste si všimli, že namiesto použitia this.carTypesme použili Car.this.carType.

Je to preto, že ak by sme neuviedli názov vonkajšej triedy Car, potom thisbude kľúčové slovo predstavovať člena vo vnútornej triede.

Podobne pristupujeme aj k metóde vonkajšej triedy z vnútornej triedy.

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

Je dôležité poznamenať, že hoci getCarName()ide o privatemetódu, sme k nej schopní vstúpiť z vnútornej triedy.

Statická vnorená trieda

V Jave môžeme tiež definovať statictriedu v inej triede. Takáto trieda je známa ako static nested class. Statické vnorené triedy sa nenazývajú statické vnútorné triedy.

Na rozdiel od vnútornej triedy nemá statická vnorená trieda prístup k členským premenným vonkajšej triedy. Je to preto, lebo statická vnorená trieda nevyžaduje, aby ste vytvorili inštanciu vonkajšej triedy.

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

Tu vytvárame objekt statickej vnorenej triedy jednoduchým používaním názvu triedy vonkajšej triedy. Vonkajšiu triedu teda nemožno odkazovať pomocou OuterClass.this.

Príklad 3: Statická vnútorná trieda

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

Výstup :

 Celkový počet portov = 3

Vo vyššie uvedenom programe sme vo vnútri triedy MotherBoard vytvorili statickú triedu s názvom USB. Všimnite si riadok,

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

Tu vytvárame objekt USB pomocou názvu vonkajšej triedy.

Teraz sa pozrime, čo by sa stalo, keby ste sa pokúsili získať prístup k členom vonkajšej triedy:

Príklad 4: Prístup k členom vonkajšej triedy vo vnútri statickej vnútornej triedy

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

Pri pokuse o spustenie programu sa zobrazí chyba:

 chyba: nestatická premenná, na ktorú sa nedá odkazovať zo statického kontextu

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.
  • Nestatické vnorené triedy (vnútorné triedy) majú prístup k ostatným členom vonkajšej / uzatvárajúcej triedy, aj keď sú vyhlásené za súkromné.

Zaujímavé články...