Java Internal classes

Source: Internet
Author: User

The following is Google Translate from https://www.tutorialspoint.com/java/java_innerclasses.htm:

in Java, like a method, a variable of a class can have another class as its member. in Java, another class is allowed to be written in one class. the class that is written is called an inner class , and the class that holds the inner class is called an external class .

Grammar:

The following is the syntax for writing nested classes. here, the class outer_demo is the outer class, andtheinner_demo class is the inner class.

class Outer_demo {   class  Nested_demo {   }}

The inner classes fall into two categories:

    • non-static inner class -This is a non-static member of the class.
    • static inner class -This is a Static member of the class.

First, inner class (non-static inner class)

The inner class is a security mechanism in Java. A class cannot be associated with an access modifier PR ivate Associate , but if the class is a member of another class, the inner class can be set to private. This is also used to access private members of the class.

There are three types of inner classes, depending on their definition and location. They are:

    • Inner class
    • Method local Inner class
    • Anonymous inner class

1. Inner class

It is very simple to create an inner class. You only need to write a class in the class. Unlike classes, an inner class can be private, and once an inner class is declared private, it cannot be accessed from an object other than the class.

The following is a program that creates an internal class and accesses it. in the given example, the inner class is private and a method is used to access the class.

Example:

classOuter_demo {intnum; //Inner class   Private classInner_demo { Public voidprint () {System.out.println ("This was an inner class"); }   }      //accessing he inner class from the method within   voidDisplay_inner () {Inner_demo Inner=NewInner_demo ();   Inner.print (); }}    Public classMy_class { Public Static voidMain (String args[]) {//instantiating the outer classOuter_demo Outer =NewOuter_demo (); //Accessing the Display_inner () method.Outer.display_inner (); }}

as you can see here, Outer_demo is an external class, Inner_demo is an inner class, Display_inner () is the method that is instantiating the inner class, and from the Main method to call this method.

If you compile and execute the above program, you will get the following results:

class.

Access to Private members:

as mentioned earlier, the inner class is also used to access the private members of the class. Suppose a class has private members accessing them. in which you write an inner class that returns a private member from the method of the inner class, such as getValue (), and finally calls the GetValue () method Class of the inner class from another class from which to access the private member.

to instantiate an inner class, you must initially instantiate the subclass. Thereafter, using an object of the outer class, the following is how the inner class is instantiated.

New= outer. New Inner_demo ();

The following program shows how to use an inner class to access a private member of a class.

Example:

classOuter_demo {//private variable of the outer class   Private intnum = 175; //Inner class    Public classInner_demo { Public intGetnum () {System.out.println ("This is the Getnum method of the inner class"); returnnum; }   }} Public classMy_class2 { Public Static voidMain (String args[]) {//instantiating the outer classOuter_demo Outer =NewOuter_demo (); //instantiating the inner classOuter_demo.inner_demo Inner = Outer.NewInner_demo ();   System.out.println (Inner.getnum ()); }}

If you compile and execute the above program, you will get the following results:

Class
175

2. Method local Inner class

In Java, you can write a class in a method, which will be a local class. like local variables, the scope of an inner class is limited within a method.

methods local inner classes can only be instantiated in methods that define inner classes. The following program shows how to use the method local inner class.

Example:

 Public classOuterclass {//instance method of the outer class   voidMy_method () {finalintnum = 23; //method-local Inner class      classMethodinner_demo { Public voidprint () {System.out.println ("This is method inner class" +num); }         } //end of inner class//accessing the Inner classMethodinner_demo inner =NewMethodinner_demo ();   Inner.print (); }       Public Static voidMain (String args[]) {Outerclass outer=NewOuterclass ();                 Outer.my_method (); }}

If you compile and execute the above program, you will get the following results:

 class

3. Anonymous inner class

An inner class that is declared as having no class name is called Anonymous Inner class . In the case of anonymous inner classes, declare and instantiate them at the same time. Typically, when you need to override methods for classes or interfaces, they are used. The syntax for an anonymous inner class is as follows:

Grammar:

New Anonymousinner () {   publicvoid  My_method () {      ...      . ........   }   };

The following program shows how to use anonymous inner classes to override a class's methods.

Example:

Abstract classAnonymousinner { Public Abstract voidmymethod ();} Public classOuter_class { Public Static voidMain (String args[]) {Anonymousinner inner=NewAnonymousinner () { Public voidMyMethod () {System.out.println ("This was an example of anonymous inner class");      }      };       Inner.mymethod (); }}

If you compile and execute the above program, you will get the following results:

Class

In the same way, you can override methods for specific classes and interfaces that use anonymous inner classes.

Anonymous inner class as proof:

In general, if a method accepts an object of an interface, an abstract class, or a concrete class, you can implement an interface, extend an abstract class, and pass an object to a method. If it is a class, you can pass it directly to the method.

However, in all three cases, the anonymous inner class can be passed to the method. This is the syntax for passing an anonymous inner class as a method parameter:

Obj.my_method (new  My_class () {   publicvoid do () {      ...      .....   }});

The following program shows how to pass an anonymous inner class as a method parameter.

Example:

//InterfaceInterfaceMessage {String greet ();} Public classMy_class {//method which accepts the object of interface Message    Public voidDisplayMessage (Message m) {System.out.println (M.greet ()+ ", this is a example of anonymous inner class as an argument"); }    Public Static voidMain (String args[]) {//instantiating the classMy_class obj =NewMy_class (); //Passing an anonymous inner class as an argumentObj.displaymessage (NewMessage () { PublicString greet () {return"Hello";   }      }); }}

If you compile and execute the above program, it will be the following result:

class as an argument

4. Static internal class

A static inner class is a nested class that is a static member of an external class. External classes can be accessed using other static members. Just like static members, static nested classes cannot access instance variables and methods of external classes. The syntax for a static nested class is as follows:

Grammar:

class myouter {   staticclass  Nested_demo {   }}

Instantiating a static nested class is a little different from instantiating an inner class. The following program shows how to use a static nested class.

Example:

 Public class Outer {   staticclass  Nested_demo {      publicvoid  my _method () {         System.out.println ("This is my nested class");      }   }        Public Static void Main (String args[]) {      new  Outer.nested_demo ();           Nested.my_method ();   }}

If you compile and execute the above program, you will get the following results:

Class

Test Project: Https://github.com/easonjim/5_java_example/tree/master/javabasicstest/test16

Java Internal classes

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.