Java Internal classes

Source: Internet
Author: User
Tags instance method

A Java inner class or nested class is a class that is declared in a class or interface. We use an inner class to logically group classes and interfaces in one place so that it is more readable and maintainable. In addition, it can access members of external classes, including private data members and methods.

Advantages of the Inner class:
    1. Nested classes represent a special type relationship: All data members and methods that can access an external class (including private)
    2. Nested classes are used to develop more readable and maintainable code because it logically groups classes and interfaces in only one place.
    3. Code optimization: it requires less code
Problem:
    1. What is the internal code generated by the editor for member Inner Class (member inner classes)?
    2. What are the two ways to create annonymous inner class (anonymous inner Class)?
    3. Can we access non-final local variables in the local inner class (partial inner classes)?
    4. How do I access static nested class (statically nested classes)?
    5. Can I define a class in an interface?
    6. Can I define an interface in a class?
Nested class (nested Class) and inner class (inner class) are different from the contact

Inner classes are part of a nested class, and non-static nested classes are considered inner classes

Types of nested classes

There are two types of statically nested classes and non-static nested classes. Non-static nested classes are considered inner classes

    • Non-static Nested class (inner Class) non-static nested classes:
      1. member Inner class (member inner classes)
      2. Annonymous Inner Class (anonymous inner classes)
      3. Local inner class (partial inner classes)
    • Static nested class statically nested classes
1. member Inner class

A non-static class that is created inside a class but outside of a method is called a member inner class. Grammar:

1 classtestmemberouter1{2  Private intData=30; 3  classinner{4   voidMsg () {System.out.println ("data is" +data);} 5  }  6   Public Static voidMain (String args[]) {7TestMemberOuter1 obj=NewTestMemberOuter1 (); 8Testmemberouter1.inner In=obj.NewInner (); 9 in.msg (); Ten  }   One}
How the members inner classes work:

The Java compiler creates two class files in the case of an internal class. The class file name for the inner class is "Outer$inner". If you are instantiating an inner class, you must create an instance of the outer class . in this case, an instance of an inner class is created in an instance of an external class.

Compiler-generated internal code:

The Java compiler creates a class file named "Outer$inner". The member inner class has a reference to the outer class , which is why the member inner class can access all data members of the external class

 import   Java.io.PrintStream;  class   Outer$inner { final  Outer ;          Outer$inner () { super   ();  this  = Outer. this        void   msg () {System.out.pri Ntln (( new  StringBuilder ()). Append ("Data is"  (Outer.      This  
2. Anonymous inner class

A class without a name is called an anonymous inner class in Java. If you must override a method of a class or interface, you should use it. There are two ways to create an anonymous inner class of Java

    1. Class (Can be an abstract class or a concrete Class)
    2. Interface
Java Anonymous Inner class example
1 Abstract classperson{2   Abstract voideat (); 3 }  4 classtestanonymousinner{5   Public Static voidMain (String args[]) {6Person p=NewPerson () {7   voidEat () {System.out.println ("nice fruits");} 8   }; 9 p.eat (); Ten  }   One}
How anonymous inner classes work
    1. The class is created, but its name is determined by the compiler, the compiler implements the person class, and implements the Eat method
    2. An object that creates an anonymous class that is referenced by the P reference variable of the person type.
Compiler-generated code
Import Java.io.PrintStream;   Static class extends person  {     testanonymousinner$1() {}     void  eat ()      {          System.out.println ( "nice fruits");      }  
3. Local inner class

The class created in the method is called the native inner class in Java. If you want to invoke a method of a local inner class, you must instantiate the class in that method .

Examples of local inner classes
1  Public classlocalinner1{2  Private intdata=30;//instance Variable3  voiddisplay () {4   classlocal{5    voidmsg () {System.out.println (data);} 6   }  7Local l=NewLocal (); 8 l.msg (); 9  }  Ten   Public Static voidMain (String args[]) { OneLocalInner1 obj=NewLocalInner1 ();  A Obj.display ();  -  }   -}
Compiler-generated internal classes:
1 ImportJava.io.PrintStream; 2 classlocalinner1$local3 {  4     FinalLocalInner1 This$; 5 localinner1$local ()6     {     7         Super(); 8          This$ = simple. This; 9     }  Ten     voidmsg () One     {   ASystem.out.println (localinner1.access$000 (localInner1. This));  -     }   -}

Rules:

    1. Local inner classes cannot be declared public, protected, private, only default access rights
    2. Local inner classes cannot be called by external methods
    3. A local inner class cannot access a non-final local variable before JDK1.7, but can access the final variable; after JDK1.8, the local inner class can also access the non-final local variable
4. Static nesting Classes

A static class created in a class is called a static nested class in Java. It cannot access non-static data members and methods. It can be accessed by an external class name.

    1. It can access static data members that include private external classes.
    2. Static nested classes cannot access non-static (instance) data members or methods
Examples of statically nested classes
class testouter1{    staticint data=30;     Static class inner{     void msg () {System.out.println ("data is" +data);}    }      Public Static void Main (String args[]) {    Testouter1.inner obj=new  Testouter1.inner ();    Obj.msg ();    }  

In this example, you need to create an instance of a static nested class because he contains the instance method msg (). But you don't need to create an instance of an external class, because nested classes are static and static properties, methods, classes can be accessed without objects

Compiler-Generated code:
1 ImportJava.io.PrintStream; 2 Static classTestouter1$inner3 {  4 Testouter1$inner () {}5 voidmsg () {6System.out.println ((NewStringBuilder ()). Append ("Data is").)  7 . Append (Testouter1.data). toString ()); 8 }    9}

5. Nested interfaces

An interface declared in another interface or class is called a nested interface. Nested interfaces are used to group related interfaces so that they are easy to maintain. A nested interface must be referenced by an external interface or class. It cannot be accessed directly.

Key points to remember for nested interfaces

    1. A nested interface must be public when declared within an interface, but it can have any access modifier if it is declared within a class.
    2. Nested interfaces are implicitly declared as static
Nested interfaces declare examples within an interface
Interfaceshowable{voidShow (); Interfacemessage{voidmsg (); }  }  classTestNestedInterface1Implementsshowable.message{ Public voidMsg () {System.out.println ("Hello Nested Interface");}  Public Static voidMain (String args[]) {showable.message Message=NewTestNestedInterface1 ();//upcasting heremessage.msg (); }  }
As you can see in the example above, we access the message interface through its external interface showable, because it cannot be accessed directly. Like the closet in the room, we can't go straight into the closet because we have to enter the room first. In the framework of the collection, Sun Microsystem provides a nested interface Entry,entry is a sub-interface to the map, which can be map.entry to access the code generated by the Java editor for nested interfaces
 Public Static Interface Showable$message  {    publicabstractvoid  msg ();  }
Can we define a class in the interface?

Yes, we can define a class in the interface, and the Java compiler will create a static nested class

Original address: Https://www.javatpoint.com/java-inner-class

 

Java Internal classes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.