About final, interface, internal class details for Java

Source: Internet
Author: User

First, Final keywords

The final keyword can probably be discussed in three parts: Final data, methods, classes

The first is data:

Final data is useful when it is constant, such as:

1, a never-changing compile-time constant

2, a value that is initialized at run time, and you do not want it to be changed

and a static final domain just takes up a storage space that can't be changed.

Details:

1, if it is the final basic data type: Then this value is constant, and final object reference, then this reference is not changed, but the reference inside the content can be modified, such as:

Final int[] A = {1, 2, 3, 4, 5};

Then A[i] can be modified, for example, a[i]++ (0<=i<5)

Similarly, you can try to use final to decorate an object, modify the non-final value within the object elsewhere, and find that it can be modified, such as we have a final StringBuilder object:

public class A {private final StringBuilder s = new StringBuilder ("Hello");p rivate final String ss = "abc";p ublic static V OID Main (string[] args) {A A = new A ();//stringbuilder can change the content, the string will output Helloworlda.s.append ("World"); System.out.println (A.S);//Not here, because the return is a new string, and the final reference cannot be changed//A.SS = "def";//About string and StringBuilder next blog Study}}

2. Blank final: A domain declared final but not given the initial value, at which point it can only be assigned to final by constructing the method

3. Final parameter: Indicates that he is read-only and can not be modified, in fact, this is mainly used in anonymous internal classes, such as View.onclicklistener (); This is the way we often respond to click events, if implemented in the form of an anonymous inner class, This is the rule that causes the life cycle of the anonymous inner class to be the same as the life cycle inconsistency of the local variable:

The method F is called to generate the variable i in its call stack, which results in a local inner class object Inner_object, which accesses the local variable I. When the method F () is finished, the local variable i is dead and does not exist. However: Local Inner class object Inner_ An object may also persist (it will only die if no one references the object again), and it will not end up dead with Method F (). At this point: there is a "ridiculous" result: the local inner class object Inner_object to access a nonexistent local variable i! The final way is to copy an anonymous internal class with the same value as the parameter, then the anonymous inner class is not extinct when the variable is no longer destroyed.

4, final prohibition of inheritance, the final class inside the method implicit is final

Reference: http://feiyeguohai.iteye.com/blog/1500108


5, Method: Mainly used to lock the method, do not allow inheritance to modify his meaning, even if the subclass of the final method is the same name as the parent class, this does not mean that it can inherit, but a subclass of its own method, in essence all private members will be the default when the final modification of the function, Using final also has a function to turn off "dynamic binding", what is dynamic binding and static binding can be referred to:

Http://blog.sina.com.cn/s/blog_600046120100wdza.html

Class: When the class is modified with the final, it is stated that the class is already considered perfect and for security reasons it does not need to be inherited, and all methods of the final class are implicitly final

Second, the interface

1, the first simple to identify the interface (Interface) and Abstract:

Abstract: A mechanism that simply provides an abstract method, hoping to create an abstract class to provide an interface for manipulating a series of classes, if a class contains an abstract method, the class must be declared as an abstract class

Interface: means that all implementations look like this, is to provide a completely abstract class, can be described as: interface is just a physical appearance, he needs to be declared how to work, and interface programming, interface design should depend on the actual situation, Rather than the utility interface provides a variety of indirection is the program complex, about more in the following inner class mentioned

In terms of functional characteristics, one is for manipulating subclasses, and one for describing the implementation of this interface class

2, interfaces can be inherited, inherited sub-interface extension interface method, interface can also create a constant group, which is also a very convenient tool to access the time directly: the interface name. Constant name, in the interface, these implicit is static and final, public, But these can't be empty final.

3. Nested interfaces:

1). Nested interfaces in classes: Examples of Java programming ideas:

public class A {//The default permission method declares the interface Binterface b{void f ();} Public, private internal class public class Bimp implements B{public void F () {}}private class BIMP2 implements B{public void F () {} }//declares the interface Cpublic interface c{void F () with public method;} Default permissions, private internal classes class Cimp implements C{public void F () {}}private class CIMP2 implements C{public void F () {}}private I Nterface d{void f ();} Private class Dimp implements D{public void F () {}}public class DIMP2 implements D{public void F () {}}public D getd () {Retu RN new DIMP2 ();} Private D dref;public void ReceiveD (d d) {dref = D;dref.f ();}}
Main method:
public class Main {public static void main (string[] args) {//TODO auto-generated method Stuba A = new A ();//cannot be accessed directly at first a.d// A.D ad = a.getd ();//A.DIMP2 Di2 = a.getd (); cannot return D because it is private a.dimp2 Di2 = (DIMP2) a.getd ();//needs to be transformed downward to compile//a.getd (). f (); cannot be compiled because D is private and the returned D cannot access a.received (A.GETD ()) in other classes;//This can, and does not directly access to the private domain of a}}

And the interface nested inside the interface:

public class Nestinginterfaces {//can access A.B in this package, A.cpublic class Bimp implements A.b{public void F () {}}class Cimp implements a.c{public void F () {}}//but A.D is private and cannot be A.D to implement it//can implement a nested interface the outermost layer class Eimp implements e{public void G () {}}// can also be implemented inside an interface class Egimp implements E.g{public void F () {}}//can also be implemented in an inner class mode of two classes EIMPL2 implements E{public void G () {}CLA SS EG implements e.g{public void F () {}}}//can also reverse the above, implement e.g first, and then implement E} in the inner class

Iii. Internal class1. The inner class refers to another class defined within a class, and the. class file name generated by the Java compilation inner class is: Outerclass$innerclass, If an inner class object is created outside the non-static method of the outer class: Outclassname.innerclassname
public class B {public static int i = 0;STATIC{SYSTEM.OUT.PRINTLN ("Hello");} Public C GetC () {return new C ();} public class C{{system.out.println ("World");}} public class A {public static void main (string[] args) {b b = new B (); B.C C = B.getc ();}} public class A {public static void main (string[] args) {b b = new B ();//b.c C = new B.C (); cannot be compiled, this can be: b c c = b.new C (); b . c C = b.getc ();}}

In fact, when the inner class is created, he will secretly capture a reference to an external class, and when we create an instance of B, the inner class is not created yet, this can be tested on its own (like the above C as a construction block, new B when the building block of C is not executed) when we create C, If C has a member variable of B, C is accessible, at the creation level does not seem to have any connection to the two classes, in addition to internal and external relations, but can access the perimeter class on the access level of the member variables, is not very interesting ~ hehe, to enable him to access all members of the external class without any special conditions. In general, we can manipulate the object of the outer class through the code of the inner class, the greater advantage of the inner class is that the inner class can implement an interface, and he has no particular relationship with whether the external class implements the interface, so to speak, He is a supplement to the Java multiple inheritance problem can be illustrated by the following examples: 1) in a class to implement two interfaces, in addition to the ordinary implement two inteface, we can also through the internal class method to achieve him: see two interfaces:
Public interface A {public void TestA ();} Public interface B {public void Testb ();}
We implement it in a common way:
public class X implements a, b{@Overridepublic void TestA () {//logic to implement a interface} @Overridepublic void Testb () {//logic to implement B interface}}
You can also use the inner class method to implement:
public class Y implements a{@Overridepublic void TestA () {//Process a logic}b Makeb () {<span style= "White-space:pre" ></ Span>return new B () {@Overridepublic void Testb () {//Handle B's Logic}};}}
When using the B function to Y implementation, direct Y.makeb () returns the anonymous inner class instance defined at Y
2) for the above situation our condition is to use inteface, but, if we do not inteface, but abstract class, this time can only use extends method to achieve a function, but also need to extends more than one class, Take a look at the following methods to handle multiple inheritance:
public class D {public void TestD () {}}public abstract class E {public void Test () {}}
One is the ordinary class, one is the abstract class, we can integrate the ordinary class, is to use the inner class to implement the abstract class method to handle multiple inheritance, through the internal class inheritance, provides the operation of the external class behavior
public class Z extends D {@Overridepublic void TestD () {//Process d}e Makee () {return new E () {@Overridepublic void Test () {//Process E }};}}
As an inner class, there is a natural feature in dealing with multiple inheritance, such as: 1) Inner classIndependence, each inner class can have his own specific state information, but can be independent of the external class, he has no is-a relationship, he is a separate entity 2) can usemultiple internal classes inherit, implement the same interface and class3) The time to create an inner class does not depend on the creation of an external class, as we have just said, you can use outclassname.innerclassname outside of a non-static method of an external class to create an inner class
2, the inner class can not only be defined in the scope of the method, but can be defined within the scope of the method, but only within the scope of use it, for example, in the IF () statement inside the IF statement to use, not beyond its scope, the detailed code does not list 3, Anonymous inner class: it is worth noting that an instance of an anonymous inner class is initialized, it can achieve the effect of creating a constructor for an anonymous inner class, and if there is a constructor for the inner class, then the value can be initialized by a parameter when the anonymous inner class is created, at which point the initialized argument is not necessarily FINA. Because he does not use the anonymous inner class directly, why use final, you can see the final details of the above 4, according to the internal class independence and security, which is well applied to the factory model: Generally speaking, the factory method is not used in the internal class to achieve, The detailed factory method model will be summarized in another blog. Assuming there are two service classes, and I want to use the factory method to produce them, we first define a common interface service and a factory interface for them.
public interface Service {void method1 (); void Method2 ();} Public interface Servicefactory {Service getService ();}
In order to maintain the independence and safety of the manufacturing process, the production process is encapsulated in the service class as an internal class.
public class Implementation1 implements Service {//Private construction method, prohibit external creation of instance through new private Implementation1 () {}//implements the factory interface with anonymous internal classes, Create instance public static Servicefactory factory = new Servicefactory () {@Overridepublic Service GetService () {//TODO Auto-genera Ted Method Stubreturn new Implementation1 ();}}; @Overridepublic void Method1 () {System.out.println ("Implementation1 method1"); @Overridepublic void Method2 () {System.out.println ("Implementation1 method2");}}

public class Implementation2 implements Service {private Implementation2 () {}public static servicefactory factory = new Ser Vicefactory () {@Overridepublic Service getService () {return new Implementation2 ();}}; @Overridepublic void Method1 () {System.out.println ("Implementation2 method1"); @Overridepublic void Method2 () {System.out.println ("Implementation2 method2");}}

So we can use it like this:
public class Factories {public static void Serviceconsumer (servicefactory fact) {Service s = fact.getservice (); S.method1 ( ); S.method2 ();} public static void Main (string[] args) {Serviceconsumer (implementation1.factory); Serviceconsumer ( implementation2.factory);}}
This way, the client program apes don't have to care about how factories produce instances of classes, they only need to invoke factory methods to get instances
Generally speaking, the factory needs to use the interface (the abstract factory in this section is very obvious), so it can bring us "let the subclass to make the decision" this feature, let subclasses to produce the classes we need-they do not know in the high-level framework of what class to produce. In this case, the method of using internal classes to implement the Factory method, and does not follow the principle of priority interface programming, in fact, sometimes, depending on the situation, we are preferred to use the Class 5, in addition to the use of internal classes to implement a factory method, but also involves another mode: Command mode-use internal classes to provide a framework to respond to the needs of a series of events, the command pattern is summarized in another blog post.
Application framework: A class or set of classes that are designed to solve a particular type of problem. To apply an application framework, you typically inherit one or more classes and override some methods. In the overridden method, write code to customize the generic solution provided by the application framework. The (Template method mode) control framework is a special kind of application framework that he uses to address the needs of responding to events. The system used primarily to respond to events is called an event-driven system.
This example involves a command pattern, but reading does not create a barrier: There is a control framework, and his job is to execute the event when the event is ready (this example is a time-triggered event)
public  Abstract class Event {Private long eventtime;protected final long delaytime;public event (long delaytime) {this.delaytime = Delaytime;start ();} Gets the current time, plus a delay time, the time that the trigger was generated//can be restarted by calling start Timer, System.nanotime () is the current exact time//If you need to repeat an event, simply call the Start method in action , but only if this event exists in the list of working controller classes public void Start () {eventtime = System.nanotime () +delaytime;} When the current time reaches the time to execute the public, the Boolean ready () {return system.nanotime () >=eventtime;} public abstract void action (); public class Controller {private list<event> eventlist = new arraylist<event> ();p ublic void addevent (Event c) {Eventlist.add (c);} Traverse EventList, look for ready, to run event object public void Run () {while (Eventlist.size () >0) {// The copy of EventList is for you to change his//sync feeling for when you visit eventllist for (Event e:new arraylist<event> (eventlist)) {if (E.ready ()) { System.out.println (e); e.action (); Eventlist.remove (e);}}}} 
Here the control framework is basically complete, and now we're going to use the inner class to provide him with concrete implementations, and he can produce multiple export versions of the same base class event within a single class. If there is now a greenhouse operation, control lights, water, temperature, bells
public class Greenhousecontrols extends Controller {//Lights private Boolean light = False;public class Lighton extends Event{p Ublic Lighton (Long delaytime) {super (delaytime);} @Overridepublic void Action () {light = true;} Public String toString () {return ' light was on ';}} public class Lightoff extends Event{public Lightoff (long delaytime) {super (delaytime);} @Overridepublic void Action () {light = true;} Public String toString () {return ' light is Off ';}} Moisture private Boolean water = False;public class Wateron extends Event{public Wateron (long delaytime) {super (delaytime);} @Overridepublic void Action () {water = true;} Public String toString () {return ' water is on ';}} public class Wateroff extends Event{public Wateroff (long delaytime) {super (delaytime);} @Overridepublic void Action () {water = false;} Public String toString () {return ' water is off ';}} Temperature (daytime, night temperature) private String thermostat = "Day";p Ublic class Thermostatnight extends Event{public thermostatnight (long Delaytime) {super (delaytime);} @OverridepublIC void Action () {thermostat = "Night";} Public String toString () {return ' thermostat is Night ';}} public class Thermostatday extends Event{public thermostatday (long delaytime) {super (delaytime);} @Overridepublic void Action () {thermostat = "Day";} Public String toString () {return ' thermostat is Day ';}} Bell public class Bell extends Event{public Bell (long Delaytime) {super (delaytime);} @Overridepublic void Action () {//Addevent, this method is called in the controller's Run method, which means that the method is executed once, Add a new Bell event to the EventList//Note that the loop condition of the Run method is that when the eventlist length is not 0, you can see that this is the addevent of the Infinite Bell (New Bell (Delaytime)); Public String toString () {return ' Bing ';}} Restart system public Class Restart extends Event{private event[] eventlist;public Restart (long delaytime,event[] eventlist) { Super (delaytime); this.eventlist = Eventlist;for (Event e:eventlist) {addevent (e);}} Like the Bell class, the reboot system repeats the list you specified into the EventList, iterating//and also adding this event to the inside @overridepublic Void action () {for (event e:eventlist) {//start is to allow the event to have a new delay trigger time E.start (); addevent (e);} Start (); Addevent (this);} Public String toString () {return ' Restart System ';}} The termination method of the system public static class Teeminate extends Event{public teeminate (long delaytime) {super (delaytime);} public void Action () {system.exit (0);} Public String toString () {return ' terminating ';}}}
Here's our Main method:
public class Greenhousecontroller {public static void main (string[] args) {greenhousecontrols gc = new Greenhousecontrols ( ); Gc.addevent (Gc.new Bell (900)); Event[] EventList = {gc.new thermostatnight (0), gc.new Lighton (+), gc.new Lightoff (+), gc.new Wateron (+), gc.new Wateroff (+), Gc.new thermostatday (1400),};gc.addevent (gc.new Restart (+ eventlist));//We mentioned earlier that GC run is continuously accessed, Because of the existence of restart and bell, if you do not want to loop, you can provide a parameter execution termination method if (args.length==1) {gc.addevent (New greenhousecontrols.teeminate (new Integer (Args[0])));} Gc.run ();}}
The above example comes from the Java programming idea, which summarizes the advantages of the inner class on the control framework: (1), the complete implementation of the control framework is created by a single class, so that the details of the implementation are encapsulated, and the inner class is used to represent the various actions (2) required to solve the problem. An inner class can easily access any member of the perimeter class, so it is possible to avoid this implementation becoming unwieldy. Without this ability, the code would be annoying so that you would choose another way
6, if the ordinary internal class declared static, then we can call him a nested class, ordinary inner class can not have static data and fields, nested class means: 1) to create a nested class object, Object that does not require its perimeter Class 2) cannot access non-static perimeter class objects from objects in the nested class of course it is not possible to use the This keyword, or you can write nested classes inside the interface (any class in the interface is implicitly static and public, does not violate the rules, and the constants are final)

About final, interface, internal class details for Java

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.