Internal and nested java classes. Part 2

    Internal and nested java classes. Part 2

    03/02/2017 - 2019

    <<< Part 1

    Part 2

    Internal classes

    Inner Classes - Internal classes The

    internal class is associated with an instance of its framing class (from the documentation).

    An example of the inner class is in the documentation.

    Create a class:

    /* Пример №7 *///classOuterClass{
        ...
        classInnerClass{
            ...
        }
    }
     

    So what's the difference, you ask. Class and nested class declarations are the
    same in these cases. The difference is that the inner class is associated with the outer class through an instance, or through a class object.

    To create an instance of an inner class, we need to first create an instance of the outer class. Then create an internal object, within the external object, in the following way:

    OuterClass.InnerClass innerObject = outerObject.new InnerClass();

    Example:

    * Пример №8 */
    package inner;
    /**
     *
     * @author Ar20L80
     */publicclassOuter{
        classInnerClass{
        }
         Outer(){
        }
        publicstaticvoidmain(String[] args){
        Outer outerObject = new Outer();
        Outer.InnerClass innerObject = outerObject.new InnerClass(); // создание экземпляра внутреннего класса
        }
    }

    In a different way, we can write this:

    /*
    Учебный пример №9
    Внутренние классы
    Получить ссылку на внешний класс в конструкторе внутреннего
     */package inner;
    /**
     *
     * @author Ar20L80
     */publicclassOuter5{
           classInner5{
                private  Outer5 myOuter;
                Inner5(){
                 myOuter = Outer5.this;
                }
           }
      publicstaticvoidmain(String[] args){
      Outer5 outer5 = new Outer5();
      }
    }
    

    Consider the properties of inner classes.

    It makes sense to use inner classes if they use parent elements in
    order not to pass on too much in constructors.

    The inner class should be used when it is not needed by anyone except the outer class.

    For example, Map.Entry - anywhere except for the Map interface and its implementations, it is not needed.

    /*
    Учебный пример №10  .
    Внутренние классы
    */package inner;
    /**
     *
     * @author Ar20L80
     */classAnyClass{} // класс от которого наследуем Inner6publicclassOuter6{
        classInner6extendsAnyClass{
        // тут мы унаследовали внутренний класс от  AnyClass{}// и можем расширить функциональность класса AnyClass{} // и класса Outer6
        }
    }
    

    In this example, we have, in fact, obtained multiple inheritance, and we can use the functionality of the AnyClass class and the functionality of the Outer6 class.

    Let's add an example.

    /*
    Учебный пример №11
     Внутренние классы
     */package inner;
    /**
     *
     * @author Ar20L80
     */classAnyClass2{
    voidanyClass2Method(){}
    }
    publicclassOuter7{
        privateint iOuterVar;
        privateclassInner7extendsAnyClass2{
            private Outer7 out7;
            publicInner7(){
                out7 = Outer7.this; // ссылка на окружающий класс
            }
            privateintanyMethodOfInner7(){
                super.anyClass2Method();// можем вызвать метод нашего супер класса AnyClass2return out7.iOuterVar; // можем обратиться к переменным // и методам Outer7
            }
        }
    }
    

    This example shows that we can use both the fields and methods of the “surrounding” class - Outer7, as well as the fields and methods of the class from which we inherited the inner class - AnyClass2.
    This gives us some great features and flexibility when using the inner class.

    Advice from the book “Java Philosophy. Bruce Ekkel. ISBN 5-272-00250-4 ”c. 313:
    “Each inner class can independently inherit a specific implementation.

    The inner class is not limited to inheritance in situations where the outer class already inherits the implementation. ”
    To use an inner class outside of the usual methods of the “surrounding” class, you must create an inner class object as follows.
    External Class Name. Internal Class Name.

    The inner class object stores information about the place where it was created.

    To be continued ...
    Part 3 >>>

    Literature by

    Michael Morgan. “Java 2. Developer Guide” ISBN 5-8459-0046-8
    Bruce Ekkel. “The Java Philosophy.” ISBN 5-272-00250-4
    Herbert Schildt “Java. Complete guide. 8th edition. ”ISBN: 978-5-8459-1759-1

    References:

    ru.wikipedia.org
    src-code.net/lokalnye-vnutrennie-klassy-java

    Oracle Documentation

    Also popular now: