Java Programming Idea: the 10th chapter Inner class

Source: Internet
Author: User

You can place the definition of one class inside another class, which is the inner class.

1. You can implement hidden

2. Internal classes understand the perimeter class and can communicate with it, often writing more elegant and clear code

10.1 Creating an inner class

public class outer{

Class inner{

}

}

If you want to create an inner class object from anywhere outside the non-static method of the outer class, you must specify the type of the object: Outerclassname.innerclassname

10.2 Linking to external classes

How does an inner class automatically have access to all members of the Wai class? When the outer class object is created with an inner class object, the inner class object must secretly capture a reference to that outer class object, which is accessed using this reference when accessing the members of an external class object. The compiler helps us deal with these details, and when we use them, it's like the inner class itself. Therefore, non-static inner classes must be created by external class objects when they are created.

10.3 using. This and. New

If you want to use a reference to an external class object, outerclassname.this to get it, the compiler checks if the type is correct and there is no runtime overhead.

Create an inner class object: To have an outer class object Outer o = new Outer (), and then create an inner class object with an Outer class object Outer.Inner i = O.new Inner (); o.new Outer.Inner () is not allowed;

10.4 Internal class upward transformation

When the private inner class is transformed upward into a base class, especially an interface, the inner class has its place: the implementation of this interface can be completely hidden, completely invisible, because the interface reference is returned

Refer to Java source Abstractlist class:

Public iterator<e> Iterator () {

return new Itr ();

}

Private class Itr implements Iterator<e> {

...

}

When we use iterators in the outside world,

Iterator iter = Arraylist.iterator ();

Can only get the interface reference, completely do not know inside is a private inner class, because ITR is private, and can not create it.

10.5 Inner classes within methods and scopes

Local inner class: defined in the method body or in a scope, out of scope cannot be used.

Note: The inability to use means that the type cannot be accessed externally, but the type is actually present in the JVM, even if the scope has ended.

10.6 Anonymous Inner class

An inner class that has no name, can have a parameter constructor, and can add and initialize the domain.

If an external object is to be used inside the inner class, the reference to the object needs to be final. The parameters used in the constructor do not need to be final.

Anonymous inner classes cannot add constructors themselves (because they cannot be accessed and have no names), and they can be implemented with code blocks when some initialization is required.

Anonymous inner classes are compared to formal inheritance, either extending the class or implementing an interface, not both, and implementing only one interface.

10.6.1 re-visit factory method

You can change the factory method to an anonymous inner class.

Interface Game{boolean move ();}

Interface Gamefactory{game getgame ();}

Class Checkers implements game{

Private Checkers () {}

private int moves = 0;

private static final int MOVES = 3;

public static Gamefactory factory = new Gamefactory () {

Public Game Getgame () {return new Checkers ();}

};

public boolean move () {

return ++moves! = moves;

}

}

10.7 Nested Classes-static inner classes

1) Creating a static inner class object does not require an external class object

2) non-static members within the perimeter cannot be accessed from a static inner class object

Normal inner class can not have static field, static can have

Classes inside the 10.7.1 interface

Under normal circumstances, there is no code inside the interface, but nested classes can be placed. Any classes that are placed in the interface are public static .

Purpose: If you want to create some common code so that they can be used by all implementations of this interface, it is very convenient to nest inner classes in the interface.

10.7.2 accessing external class members in a multilayer nested class

It does not matter how many layers an inner class is nested, it can transparently access all members of all the perimeter classes.

Class mma{

private void F () {}

Class a{

private void G () {}

public class b{

void H () {

f ();//Direct Call no problem

g ();

}

}

}

}

10.8 Why internal classes are required

In general, an inner class inherits a class or implements an interface, and can manipulate the perimeter class object.

Core reason: The inner class can provide multiple inheritance capabilities.

For example: Abstractlist has ITR and listitr two kinds of iterators, if we just let abstractlist implement iterator interface, then we can only write an iterator, by using the internal class method can add multiple iterators.

10.8.1 Closures and callbacks

If there is a class that needs to implement an interface to provide a method, but finds that the method has already been used by another interface, you can use the inner class instead of the class to implement the interface.

The value of a callback is its flexibility---can dynamically determine what method to invoke at run time.

10.8.2 internal class and control framework

Design a control framework that requires a set time to perform the corresponding event:

Create an abstract event class with execution time and delay time to calculate execution time with delay time when a new event is generated, and the action method is implemented by the implementation class.

Public abstract class event{

Private long eventtime;

Protected final long delaytime;

Public Event (long delay) {

This.delaytime = delay;

Start ();

}

public void Start () {

Eventtime = System.nanotime () + delaytime;

}

public Boolean Ready () {

return system.nanotime >= eventtime;

}

public abstract void action ();

}

Create a control class that loops through all events and executes the action if the event time is up

public class controller{

Private list<event> EventList = new arraylist<> ();

public void Addevent (Event e) {eventlist.add (e);}

public void Run () {

while (Eventlist.size () >0) {

for (Event e:eventlist) {

if (E.ready) {

E.action ();

Eventlist.remove ();

}

}

}

}

}

From the design of these 2 classes above, we have no idea what the event specifically does, but the core function of our entire control framework is "to separate the things that change (the event implementation) from the unchanging (the process of time)." And we just need to create a different event, which is exactly what the inner class is going to do:

1) implementations in the control framework are created by a single class, which enables the implementation details to be encapsulated. The inner class is used to represent the different actions necessary to resolve the problem.

2) Internal classes can easily access external class members, and this implementation does not seem awkward.

Control framework:

public class Greenhousecontrols Extend controller{

Private Boolean light = false;

public class Lighton extends event{

Public Lighton (long delay) {super (delay);}

public void action () {

Hardware control code to turn on light

Light = true;

}

}

public class Lightoff extends event{...}

Private Boolean water = false;

public class Wateron extends event{

Public Wateron (long delay) {super (delay);}

public void action () {

//..

Water = true;

}

}

//... Other internal classes

}

The control framework hides the implementation details with internal classes.

So how do you use this framework and perform the required events:

public static void Main (string[] args) {

Greenhousecontrols gc = new Greenhousecontrols ();

Gc.addevent (gc.new Lighton (100));

Gc.addevent (gc.new Lightoff (200));

...

Gc.run ();

}

The control frame can reflect the value of the inner class, and the graphic interface design is more convincing.

10.9 Inheritance of inner classes

Java Programming Idea: the 10th chapter Inner class

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.