Kind-Explain the use of interfaces and internal classes in Java

Source: Internet
Author: User
Tags class definition modifiers

First, the interface

    • Understanding of the interface

Java interface is the declaration of a series of methods, is a collection of methods features, an interface only the method of the characteristics of the implementation of the method;

That is, the interface itself provides the basic declaration of the method without providing the method body; The method declared in the interface can only be implemented by implementing the subclasses of the interface.


interfaces are another very important structure in Java. Because Java does not support multiple inheritance, in some ways this also creates some limitations.

Therefore, the interface allows multiple implementations of the features to compensate for the class can not be more inheritance shortcomings. Often through the dual design of inheritance and interface, it is possible to maintain the data security of the class and implement multiple inheritance in disguise.


    • Features of the interface
    1. Use the keyword "interface" to declare an interface; Use the keyword "implements" to declare a class to implement an interface. The
    2. is the same as the permission limit of the class, and the interface can only be declared as "public" or the default modifier.
    3. The variables declared in the interface are automatically set to public, static, final, That is, the variables declared on the interface will actually be implicitly promoted to "public static constants"
    4. interface itself cannot be constructed instantiated, but can be instantiated by implementing the class of that interface.
    5. If the class that implements the interface is not an abstract class, then the class must implement the methods in the interface.
    6. Interfaces and interfaces can also be inherited. A child interface can also define a new method declaration, in addition to all method declarations that have a parent interface.

according to the characteristics of the interface, we can actually see that the interface is actually more like declaring a specification, which is equivalent to implementing a framework that defines a program. For example, as a remote-controlled car designer. You may need to provide some specifications to these remote control car manufacturers, let them according to your design specifications for the production of remote control cars.

Package Com.tsr.j2seoverstudy.interface_demo;public interface Moveable {void TurnLeft (); void TurnRight (); void stop ();}
This is the interface you provide for the mobility of the toy car (moveable), and the manufacturer must implement it according to the specification of the interface in order for the car to move successfully.


    • The difference between an interface and an abstract class
    1. A class can implement multiple interfaces, but can inherit only one abstract class.
    2. A non-abstract method can exist in an abstract class, but the method declared in the interface must be abstract.
    3. The methods in an abstract class can be any access, but the methods in the interface are public permissions.
    4. can exist in an abstract class any type of instance domain (variable, etc.) that you define, but the domain in the interface is public, static, and final.

The greatest similarities between abstract classes and interfaces may lie in the common characteristics of the objects in their system, which are constantly being drawn upward. They can all be used for polymorphic implementations.


Second, the internal class


1. What is an internal class?

As the name implies, an inner class refers to a class that is defined inside another class. We know that one of the basic forms of Java writing is a class, and the structure of a class is usually made up of domains (static domains, instance domains), and methods. And sometimes there is another component in a class, which is an inner class.


2. Why use internal classes?

In this regard, the JAVA2 study guide says: "You are an OO ape, so you know that for code reusability and Flexibility (extensibility), you need to keep the class private enough." That is, a class should have only the code that the class object needs to execute, and any other operations should be placed in other classes that are more appropriate for those tasks. But! Sometimes it appears that one of the actions required in the current class should be more appropriate in a separate special class, because the classes are sufficiently specialized, but unfortunately, these operations are closely related to the current class (for example, members (including private members) that are used in the current class, and so on). It is this kind of situation that prompted the birth of the inner class.


More specifically, the reason for the use of internal classes is usually mainly:

    • Within the inner class, you can access any data in the scope of the class definition, including private data. (This is because the inner class implicitly holds an object reference to the external class: "External class name. This")
Package Com.tsr.j2seoverstudy.base;public class Outer {private int num = 5;private class Inner {void Printouternum () {/* * 1. Verifies that an inner class can access any property within the scope of its definition, including properties declared as private. * 2. The intrinsic class has access to the instance properties of the external class because it implicitly holds an object of the outer class: the External class class name. This */system.out.println (num); System.out.println (Outer.this.num);}}}
As you can see in the example above, although the variable "num" in the outer class "Outer" is declared private, the inner class defined in "Outer" can still access the member variable.


    • Inner classes are able to hide themselves from other classes that exist under the same package. In simple terms, the benefit is the encapsulation of a more sophisticated class.
Package Com.tsr.j2seoverstudy.base;class Outer {private int num = 5;//Method interface exposed to others public void Exposemethod () {Inner in = NE W Inner (); System.out.println (In.dosomethingsecret ());} Private class Inner {int Dosomethingsecret () {//Encapsulate some method that you do not want to expose to anyone else's details System.out.println ("Concealed method, Diao!"); return num;}}} /* * The program output is: * Concealed method, Diao! * 5 */public class test{public    static void Main (string[] args) {Outer out = new Outer (); Out.exposemethod ();}}
With this example we can see the rigorous encapsulation that comes with the internal class implementation. We accomplished a series of "secret operations" through the internal class "Inner" method "Dosomethingsecret".

But when we provide it to others, the details exposed to the user are only one method in the outer class "Exposemethod". This is good for our purpose to hide the actions that you don't want others to know about.


We know that in general, the access rights of a class can only be modified to public or default. This means that even if we choose a relatively small access rights: The default package access rights.

The implementation details of the class that we define will also be exposed to other classes in the same package.

The inner class is allowed to be declared as pirvate. This means that other classes do not even know that we have defined such a class, not to mention the implementation details of the class.


    • the anonymous inner class makes it easier to define callback functions. take the multithreading mechanism in Java as an example:

If you do not use an inner class, then we should implement it as follows:

Package Com.tsr.j2seoverstudy.base;public class Innerdemo {public static void main (string[] args) {Assignment assignment = new Assignment (); Thread t = new thread (Assignment); T.start ();}} Class assignment implements runnable{@Overridepublic void Run () {SYSTEM.OUT.PRINTLN ("thread Task");}}
with anonymous inner classes, we can simplify the implementation to:
Package Com.tsr.j2seoverstudy.base;public class Innerdemo {public static void main (string[] args) {thread t = new Thread (n EW Runnable () {@Overridepublic void run () {SYSTEM.OUT.PRINTLN ("thread Task");}}); T.start ();}}
as I said in my previous review, "anonymity" is well understood, and the direct understanding is that there is no name. The identifiers in Java are names.

So, in the first implementation, the class name identifier "Assignment" that defines the thread task class is the class name of the thread task class.

And when we implement the task of the thread in the second way, we find that it is directly passed as a parameter to the constructor of the thread class.

Without the associated class name identifier, the thread task class is not named, so it is called "anonymous".

Note: The third way of use should be the most commonly used in actual development. The first two cases I personally in the work rarely used, but many well-known books are introduced, so may as well as an understanding, always useful when.


How to create an inner class object

As we said above, the inner class implicitly holds an object reference to the outer class to which it belongs.

It cannot be imagined that object creation of an inner class must depend on the external class to which it belongs.

In other words, it is like creating an object that uses an inner class, provided that the object to which the external class belongs is first acquired.


Internal classes are created in two ways:

    • In the outer class to which it belongs, create the Inner class object: This is no different from the way you normally create an object, that is, ClassName clazz = new ClassName ();
    • Create an inner class object in a class other than the outer class to which it belongs: because we have said that the creation of an inner class object depends on the external class to which it belongs, so this is created by: outer.inner in = new Outer (). New Inner ().

We still have a more intuitive understanding of the object creation of an inner class through a previously seen face question:

*/* Title: * 1.  public class outer{* 2. public void Someoutermethod () {* 3.//Line 3 * 4.} * 5. public class inner{} * 6. public static void Main (string[] args) {* 7.  Outer o = new Outer (); * 8. Line 8 * 9. } * 10.  } * * Which instantiates an instance of Inner? * A. New Inner (); At line 3 * B. New Inner (); At line 8 * C. New O.inner (); At line 8 * D. New Outer.Inner (); At line 8 */
It's really simple, just keep in mind that the two types of creation we said above are OK. To summarize: Before you create an inner class object, you must first construct an object of its outer class.

So when an inner class object is created in the outer class, because the outer classes themselves hold object references: this. So you can create an inner class directly.

In addition to creating an inner class object outside the outer class, you need to create a new Outer () and create an inner class object.

Let's take a look at the 4 answers to this question separately:

    • A The answer is placed on the third line of the program. is to create an inner class object in an instance method within the outer class to which it belongs, because the instance method holds the external class object reference this, so it can be created directly. Then a answer is legal.
    • b The answer is on line eighth of the program. Although an inner class object is created inside the inner class itself, it does not hold its outer class object because the code is in a static method. So B is illegal.
    • The C answer is placed on line eighth of the program. The code is in a static method, but because the outer class object "O" has been created before, the way to create an inner class object through "O" is well-done. However, it should be noted that the correct use of this approach should be "o.inner ()" Rather than "new O.inner ()". So c is also illegal.
    • The d answer is placed on line eighth of the program. At first glance, it is perfect. Note, however, that it uses "new Outer." Instead of invoking the class constructor with the new keyword to create an object in the correct way "new Outer ()." So d nature is also illegal.

It can be concluded that the legal internal class instance declaration method is only: A.


Local inner class

A local inner class is a slightly special way of using an inner class. As the name implies, it is the same as "local variable", which is defined as an inner class within a method or block of code.

About the use of local internal classes, I think the main need to master only three points:

First, as with other local members, the valid range of a local class is limited to the contained code block, and once the scope is exceeded, the local inner class cannot be accessed.

Second, the local inner class cannot be decorated with access modifiers, that is, you cannot use any of the private, protected, public modifiers. Because the scope is already scoped to the local block that is currently owned.

Third, this is often the most common reason for using local inner classes. You may also notice that the ordinary inner class can access any member of the external class to which it belongs, but the local variables within the method defined by the external class that it belongs to cannot be accessed, and a local inner class can be used to solve the problem. It must be remembered, however, that variables accessed by local internal classes must be decorated as final.

public class Partinnerdemo {    int num_1 = 10;public void Method () {final int num_2 = 5;class partinner{   private void Innermethod () {  System.out.println (num_1+num_2);}}}    


Static inner class (nested Class)

The static inner class can be said to be a wonderful flower in the inner class. For a joke, the reason for this is that the static inner class is a special kind of inner class.

Its properties are more like a nested class than an inner class. Because we said it before. In general, the inner class implicitly holds an object reference to the outer class to which it belongs. The static inner class does not.

In addition, static data cannot exist in any non-static inner class. Therefore, if you want to declare static data in an inner class, the inner class must also be declared static.

Of course, static classes can also declare instance data in addition to static data. The difference is that:

If you want to use static data in a static inner class outside of it, you can pass it directly through the inner class: the class name. static member name.

If you want to use only instance members in the static inner class, you must first create an object of that inner class, just like any other non-static inner class.

At the same time, however, it is important to note that object creation of static inner classes differs from normal inner classes because we know that the static inner class itself does not hold an object reference to the outer class, so it does not depend on the object of the outer class. Simply put, we can assume that the static inner class itself is a static member of the external class, so its object is created in the following way: Outer.Inner in = new Outer.Inner ();

public class Staticinner {void Test () {int num_1 = Inner.num_1;//inner in = new Inner (); int num = In.num;}   private static class Inner {int num = 5;static int num_1 = 10;}  Public     static void Main (string[] args) {Staticinner.inner in = new Staticinner.inner ();     } }

Speaking of this, I think of another question. This problem has not been able to figure out why in Java when beginners:

public class Test {public static void main (string[] args) {class inner{string Name;inner (String s) {name = S;}} Inner o = new Inner ("Test");}}

As we said earlier, all non-static instantiation of inner classes relies on object instantiation of its outer class.

In this code, however, we do not rely on the outer class of the defined local inner class "Inner" Object creation.

This should be because: because the local inner class is defined in a static method, the static method does not hold the object reference to the class to which it belongs.

In other words, a local inner class defined in a static method suffers the same restriction as a static method: it cannot access any non-static members of the external class to which it belongs.

The purpose of an inner class to hold its external class object reference is to have access to all instance members of the external class to which it belongs.

So now that I've been limited to not having access to instance members, it's natural to not have to rely on external class objects.


Anonymous inner class

As for the anonymous inner class, there are three reasons why the inner class was used, and it has been said.

The anonymous inner class is typically defined in the following format:

New Supertype (constuction parameters) {               //inner class method and Data}

For anonymous inner classes, it is simply a shorthand form of an inner class.

It is important to note that the use of an anonymous inner class is based on the premise that the inner class must inherit from an external class or implement an external interface.

As we said above about Java multithreading. Anonymous inner classes can be used because the anonymous inner class we define implements the Runnable interface.


Kind-Explain the use of interfaces and internal classes in Java

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.