Java Basics-Nested classes, inner classes, anonymous classes

Source: Internet
Author: User

The content of this article is transferred from blog: http://www.cnblogs.com/mengdd/archive/2013/02/08/2909307.html

The related classes are organized together, reducing the clutter in the namespaces.

An inner class can be defined in another class and can be defined in a function or even as part of an expression.

  the inner classes in Java are divided into four types :

  Static inner class static inner class (also called nested Class)

  member Inner class member inner class

  Local internal class local inner class

  Anonymous inner class anonymous inner class

static inner class static Inner class

The simplest form of inner class.

The static keyword is added to the class definition.

Cannot have the same name as an external class.

  is compiled into a completely separate. class file with the name Outerclass$innerclass.class in the form .

   only static members and static methods of external classes can be accessed , including private static members and methods .

The static inner class object is generated in the following way:

    Outerclass.innerclass inner = new Outerclass.innerclass ();

Static internal classes use code:

1 static internal class use Test2 3  PackageCom.learnjava.innerclass;4 5 classStaticinner6 {7     Private Static intA = 4;8 9//Static internal class of public static classes Inner11 {GB public void test () 13 {14//static internal The class can access static members of the external class 15//And it can only access static System.out.println (a);}18 - } +  A  Public classstaticinnerclasstest at { -  -      Public Static voidMain (string[] args) -     {Staticinner.inner Inner = new Staticinner.inner (); - inner.test (); in     } -}

member Inner class member Inner class

The member inner class is also defined in another class, but is not defined with a static adornment.

A member inner class and a static inner class can be likened to non-static member variables and static member variables.

The member inner class is like an instance variable.

  It can access all the member variables and methods of its outer class, whether static or non-static .

Create an instance of the member's inner class inside the outer class:

This.new Innerclass ();

Create an instance of an inner class outside the outer class (must be created by an instance of an external class):

(New Outerclass ()). New Innerclass ();

To access members of an external class in an inner class:

Outerclass.this.member

See the code example for details:

1 member internal class use Test2 3  PackageCom.learnjava.innerclass;4 5 classMemberinner6 {7     Private intD = 1;8     Private intA = 2;9 10//Define a member inner class all public class Inner212 {$ private int a = 8;14 public void Dosomethin G () 16 {17//Direct access to external class objects System.out.println (d); System.out.println (a);//Direct visit Q A, the A20 in the inner class is accessed 21//How to access a in the outer class? System.out.println (MEMBERINNER.THIS.A);}24} -  - } -  in  Public classmemberinnerclasstest - { to  +      Public Static voidMain (string[] args) -     { the  *         //create an object of a member's inner class $         //you need to create an instance of an external class firstPNS Memberinner.inner2 inner = new Memberinner (). New Inner2 (); -  the inner.dosomething (); +     } A}

Local internal class local Inner class

  local inner classes are defined in a method and are smaller than the range of methods . Is the least used type in an inner class.

  like local variables, it cannot be modified by public, protected, private, and static .

  Only local variables of the final type defined in the method can be accessed.

Local inner classes are defined in methods, so they can only be used in methods, that is, you can only generate instances of local inner classes within a method and invoke their methods .

1 member internal class use Test2 3  PackageCom.learnjava.innerclass;4 5 classLocalinner6 {7     intA = 1;8 9      Public voiddosomething ()Ten     { One         intb = 2; A         Final intc = 3;13//Define a local inner class Inner315 {17 public void Test () {18 System.out.println ("Hello World"); System.out.println (a); 20 21//No access to non-final parts Variable//Error:cannot refer to a non-final variable B inside an INNER23//class defined I n a different method24//System.out.println (b); 25 26//access to final variable Sys Tem.out.println (c);}29} - 31//Create an instance of the local inner class and call the method, new Inner3 (). Test (); -     } the } *  $  Public classlocalinnerclasstestPanax Notoginseng { -      Public Static voidMain (string[] args) the     { +         //creating an external class object ALocalinner inner =NewLocalinner (); the         //methods for calling external classes + inner.dosomething (); -     } $  $}

Anonymous inner class anonymous Inner class

The anonymous inner class is a local inner class without a name , not using the keyword class, extends, implements, and no constructor method .

An anonymous inner class implicitly inherits a parent class or implements an interface .

In the generated. class file, the anonymous class generates the outerclass$1.class file , which is based on the first few anonymous classes.

Anonymous inner classes are used more often as a method parameter.

1 Anonymous internal class usage test2 3  PackageCom.learnjava.innerclass;4 5 Importjava.util.Date;6 7  Public classAnonymouseinnerclass8 {9 Ten@SuppressWarnings ("Deprecation") One      PublicString getDate (date date) A     { -         returndate.tolocalestring (); -  the     } -  -      Public Static voidMain (string[] args) -     { +Anonymouseinnerclass test =NewAnonymouseinnerclass (); -  +         //Print Date: AString str = test.getdate (NewDate ()); at System.out.println (str); -System.out.println ("----------------"); - 26//Use the anonymous internal class of String str2 = test.getdate (New Date () 28 {29}),//use curly braces, but do not fill in the contents, execute the results and The above is exactly the same 30//generates an object that inherits the subclass of the date class to System.out.println (str2); +System.out.println ("----------------"); - 34//Use Anonymous inner class, and override method in parent class. String STR3 = test.getdate (New Date () 36 {37 38//overriding parent class                 Method of @Override40 @Deprecated41 public String tolocalestring () 42 {43 Return "Hello:" + super.tolocalestring ();}45); -  - System.out.println (STR3); the     } -}

  

Examples of using internal classes in swing are as follows:

1 using anonymous inner classes in swing2 3  PackageCom.learnjava.innerclass;4 5 Importjava.awt.event.ActionEvent;6 ImportJava.awt.event.ActionListener;7 ImportJava.awt.event.WindowAdapter;8 Importjava.awt.event.WindowEvent;9 Ten ImportJavax.swing.JButton; One ImportJavax.swing.JFrame; A  -  Public classswingtest - { the      Public Static voidMain (string[] args) -     { -JFrame frame =NewJFrame ("JFrame"); -JButton button =NewJButton ("JButton"); + Button.addactionlistener (New ActionListener () {//New come out an instance of a class that implements the ActionListener interface 2 3 @Override25 public void actionperformed (ActionEvent arg0) Ystem.out.println ("Hello World");}30}); to  +         //Join Button - Frame.getcontentpane (). Add (button); the  *         //Set shutdown Behavior $ frame.setdefaultcloseoperation (jframe.exit_on_close);Panax Notoginseng  -Frame.setsize (200, 200); the         Frame.addwindowlistener (New Windowadapter () 41 {42//) anonymous internal classes that inherit the adapter class can also be used @O verride44 public void windowclosing (WindowEvent e) {System.out . println ("Closing"); system.exit (0);}50});WuyiFrame.setvisible (true); the     } -  Wu}

(RPM) Java Basics-Nested classes, inner classes, anonymous 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.