In Java, there are 4 types of nested (nested) classes:Joshua Bloch:
- Static nested classes
- Inner classes
- Local Classes
- Anonymous (unnamed) classes
“There are four categories of nested classes:Let's try to figure out what it is."
- static member class
- nonstatic member class,
- anonymous class (anonymous class)
- and local class.
/* Пример №1 */ //: c06:Car.java // композиция с использованием открытых объектов // двигатель class Engine{ public void start(){} public void rev(){} public void stop(){} } class Wheel{ public void inflare(int psi){}// накачать } // окно class Window{ public void rollup(){}// приоткрыть public void rolldown(){}// опустить } // дверь class Door{ public Window window=new Window(); public void open(){}//открыть public void close(){}// закрыть } // машина public class Car{ public Engine engine = new Engine(); public Wheel[] wheel = new Wheel[4]; public Door left = new Door(), right = new Door();//две двери public Car(){ for(int i = 0; i<4; i++) wheel[i]= new Wheel(); } public static void main(String[] args){ Car car= new Car(); car.left.window.rollup(); car.wheel[0].inflare(72); } }
"Since the composition of the object is part of the analysis of the task (and notStatic nested classes
just part of the class implementation), declaring class members open, helps the client programmer understand how to use the class, and makes it easier for the creator to write code. However, it must be remembered that the described case is special, and basically the fields of the class must be declared private. "
A class is called nested if it is defined inside another class. That is, a class is simply defined inside another, not even important statically defined or not statically. A nested class is created to serve the class around it. If the nested class is useful in some other context, it should become a top-level class.Application
/* Пример №2 */ // class OuterClass { ... class NestedClass { ... } }
A class is called nested if it is defined inside another class "Oracle documentation can be viewed at this link: >>>
/* Пример №3 */ // class A{ ... class B { ... } }
/* Учебный пример №4 */ package innernested; /** * * @author Ar20L80 */ public class A { private static int iPrivVar; class B { void setPrivateOfA(int var) { A.iPrivVar = var; } } }
/* Учебный пример №5 Статические вложенные классы Попытка доступа к нестатической переменной внешнего класса Outer2 через обращение из вложенного статического класса Nested2 */ package nested; /** * * @author Ar20L80 * 20.03.2016 */ public class Outer2 { public int pubOutVar; // переменная не статическая и мы не имеем к ней доступа // из внутреннего статического класса private int prOutVar; public Outer2(){} static class Nested2{ public static int pub_innVar; // тут все в порядке public Nested2() {} int getOuterPublicVariable() { return Outer2.this.pubOutVar; // ошибка return Outer2.pubOutVar; // ошибка } int getOuterPrivateVariable() { return Outer2.this.prOutVar; // ошибка return Outer2.prOutVar; // ошибка } } } /* вывод программы: программа не компилируется */
/* Учебный пример №6 Статические вложенные классы Демонстрация доступа к «приватной» статической переменной внешнего класса из внутреннего статического класса 20.03.2016 */ package nested; /** * * @author Ar20L80 */ public class Outer3 { private static int prStOuterVar; public Outer3(){} static class Nested3 // Nested { int getStaticOuterVar() { return Outer3.prStOuterVar; // ok } void setStaticOuterVariable(int var) { Outer3.prStOuterVar = var; // ok } } public static void main(String[] args) { Outer3.Nested3 nestedObj = new Outer3.Nested3(); // экземпляр класса внутренний Outer3.prStOuterVar = 19; System.out.println("nestedObj.getStaticOuterVar() = "+nestedObj.getStaticOuterVar());//статическая переменная внешнего класса из экземпляра внутреннего // устанавливаем через экземпляр внутреннего класса nestedObj.setStaticOuterVariable(77); System.out.println("Outer3.prStOuterVar = "+ Outer3.prStOuterVar); } } /* Вывод программы: nestedObj.getStaticOuterVar() = 19 Outer3.prStOuterVar = 77 */
Source: https://habr.com/ru/post/439648/