Test with a knife and fly with a stupid bird
I. Interface
A Java interface is a series of methods declarations and a set of methods features. An interface has only the features of a method and has no implementation of a method;
That is to say, the interface itself provides the basic declaration of the method, rather than the method body; the method declared in the interface can only be implemented by the subclass that implements the interface.
An interface is another very important structure in Java. Because Java does not support multi-inheritance, to some extent, this also causes some limitations.
Therefore, the features that allow multiple implementations of interfaces make up for the disadvantages that classes cannot be inherited. Generally, through the dual Design of inheritance and interface, you can maintain the data security of the class and implement multi-inheritance in disguise.
Package com. tsr. j2seoverstudy. interface_demo; // The access modifier can only be public or the default access modifier public interface InterfaceDemo {// is implicitly promoted to: public static final int VAR = 50; int VAR = 50; // public void methodDemo (); // The method must be abstract} class Test implements InterfaceDemo {public static void main (String [] args) {InterfaceDemo in = new InterfaceDemo (); // compile predictioninterfacedemo in = new Test (); // you can declare the variables of the interface type and instantiate them by implementing the class of this interface.} @ Overridepublic void methodDemo () {}}
According to the characteristics of the interface, we can see that the interface is more like declaring a specification, which is equivalent to implementing a framework that defines the program. For example, a remote control vehicle designer. You may need to provide some specifications for remote control vehicle manufacturers to produce remote control vehicles according to your design specifications.
package com.tsr.j2seoverstudy.interface_demo;public interface Moveable {void turnLeft();void turnRight();void stop();}
This is what you provide to give toy cars a moveable interface. The manufacturer must follow the specifications of this interface to make the car move successfully.
- Differences between interfaces and abstract classes
The biggest difference between an abstract class and an interface is that it is a common feature that constantly extracts objects from the system. They can be used for implementation of polymorphism.
Ii. Internal class
1. What is an internal class?
As the name implies, an internal class refers to the class defined in the internal of another class. We know that the basic embodiment of a Java program is a class, and the structure of a class is usually composed of a domain (static domain, instance domain) and a method. Sometimes, an internal class is another component of a class.
2. Why Internal classes?
In this regard, the Java2 learning guide says: You are an OO programmer, so you know that classes must be sufficiently specific for code reusability and flexibility (scalability. That is to say, a class should only have the code that the class object needs to execute, and any other operations should be placed in other classes that are more suitable for such work. But! Sometimes an operation is required in the current class and should be placed in another special class. It is more appropriate to keep the class specific enough. But unfortunately, these operations are closely related to the current class (for example, they will be used to members (including private members) of the current class ). This type of situation prompted the birth of internal classes.
More specifically, the reason for using internal classes is generally:
- You can access any data, including private data, in the scope of the class definition. (This is because the internal class will implicitly hold the object reference of 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. it verifies that the internal class can access any attribute in the scope of its definition, including the attribute declared as private. * 2. the reason why the internal class can access the instance attributes of the external class is that it implicitly holds the object of the external class: the name of the external class. this */System. out. println (num); System. out. println (Outer. this. num );}}}
In the above example, although the variable "num" in the external class "Outer" is declared as private, the internal class defined in "Outer" can still access the member variable.
- Internal classes can hide themselves for other classes under the same package. To put it simply, this benefit is to bring more perfect class encapsulation.
Package com. tsr. j2seoverstudy. base; class Outer {private int num = 5; // method interface exposed to others public void exposeMethod () {Inner in = new Inner (); System. out. println (in. doSomeThingSecret ();} private class Inner {int doSomeThingSecret () {// encapsulate some methods that you don't want to expose to others for any details. System. out. println ("concealed method, Smit! "); Return num ;}}/ ** the output result of the program is: * concealed method! * 5 */public class Test {public static void main (String [] args) {Outer out = new Outer (); out. exposeMethod ();}}
Through this example, we can see the rigorous encapsulation brought about by the internal class implementation. We completed a series of "secret operations" through the "Inner" method "doSomeThingSecret ".
However, when we provide it to users, the details exposed to users are only one method in the external class "exposeMethod ". This achieves our goal and hides operations that do not want others to know.
We know that the class access permission can only be modified to public or default. This means that even if we select a relatively small access permission: the default package access permission.
The Implementation Details of the class we define will also be exposed to other classes in the same package.
Internal classes can be declared as pirvate. This means that other classes do not even know the implementation details of a class that we have defined.
- The anonymous internal class can more easily define callback functions. Taking the multithreading mechanism in Java as an example:
If you do not use an internal class, our implementation method should be 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 ");}}
Through the anonymous internal class, we can simplify the implementation:
Package com. tsr. j2seoverstudy. base; public class InnerDemo {public static void main (String [] args) {Thread t = new Thread (new Runnable () {@ Overridepublic void run () {System. out. println ("thread task") ;}}); t. start ();}}
As I mentioned in my previous review, "Anonymous" is actually very easy to understand. The direct understanding is that there is no name. The identifier in Java is the name.
Therefore, in the first implementation method, the class name identifier "Assignment" that defines the thread task class is the class name of the thread task class.
When we implement a Thread task in the second way, we find that the task is directly passed as a parameter to the constructor of the Thread class.
There is no relevant class name identifier, so this thread task class has no name, so it is called "anonymous ".
Note: The third method should be the most commonly used in actual development. I have rarely used the first two cases in my work, but I have introduced them in many well-known books. Therefore, I may wish to use them as an understanding.
How to create an internal Class Object
As we have mentioned above, the internal class implicitly holds an object reference of its external class.
Therefore, it cannot be imagined that the creation of an internal class object must depend on the external class to which it belongs.
In other words, to create an object that uses an internal class, you must first obtain the object of its external class.
There are two ways to create an internal class:
- Create an internal class object in the external class to which the object belongs: This is no different from the method used to create an object, that is, ClassName clazz = new ClassName.
- Create an internal class object in a class other than its external class: because we have said that the creation of internal class objects depends on its external class, the creation method is Outer. inner in = new Outer (). new Inner ().
We still use the interview questions we have seen before to learn more about internal Class Object creation:
/** Question: * 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? *. 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 */
In fact, it is very easy to remember the two creation conditions we mentioned above. To sum up, before creating an internal class object, you must first construct the object of its external class.
Therefore, when an internal class object is created in an external class, because the external class itself holds the object reference: this. Therefore, you can directly create an internal class.
To create an internal Class Object outside the external class, you must first create an external Class Object with new Outer () and then create an internal class object.
Here we will look at the Four answers to this question respectively:
- Answer A is placed in the third line of the program. Is to create an internal class object in the instance method of its external class, because the instance method holds the external class object to reference this, you can directly create. Then answer A is valid.
- B is placed in the eighth line of the program. Although the internal class itself creates an internal class object, because the code is in a static method, it does not hold its external class object. Therefore, B is invalid.
- The C answer is placed in the eighth line of the program. Although the Code is in a static method, it is feasible to create an internal class object through "o" because the external Class Object "o" has been created before. However, it should be noted that the correct use of this method should be "o. Inner ()" rather than "new o. Inner ()". Therefore, C is invalid.
- D. Place the answer in the eighth line of the program. At first glance, it's perfect. However, it should be noted that it uses "new Outer." instead of calling the class constructor using the new keyword to create an object. The correct method is "new Outer ().". So D is also illegal.
It can be concluded that the valid internal class instance declaration method is only:.
Local internal class
Local internal classes are a special method of using internal classes. As the name suggests, it is the same as "local variables", that is, internal classes defined in methods or code blocks.
For the use of local internal classes, I think there are only three points to master:
First, like other local members, the effective scope of a local class is limited to the contained code block. Once the range is exceeded, the local internal class cannot be accessed.
Second, the local internal class cannot be modified by the access modifier, that is, the private, protected, or public modifier cannot be used. Because the scope has been limited to the local block to which the current part belongs.
Third, this is usually the most common reason for using local internal classes. You may also notice that although a common internal class can access any member of its external class, the local variables in the method of its external class definition cannot be accessed, you can solve this problem by using local internal classes. However, you must remember that the variables accessed by local internal classes must be modified to 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 internal class (nested class)
Static internal classes can be said to be a wonderful combination of internal classes. This is a joke because static internal classes are special internal classes.
Its features are more like a nested class than an internal class. As we have mentioned earlier, generally internal classes will implicitly hold an object reference of their external classes. The static internal class does not.
In addition, no static data exists in any non-static internal class. Therefore, if you want to declare static data in the internal class, the internal class must also be declared as static.
Of course, in addition to static data, you can declare instance data. The difference is:
If you want to use static data in a static internal class, you can directly use the class name and static member name of the internal class.
To use only instance members in the static internal class, you must first create the object of the internal class, just like other non-static internal classes.
However, you must also note that the object creation of static internal classes is different from that of General Internal classes, because we know that static internal classes do not own object references of external classes, therefore, it does not depend on external class objects. Simply put, we can think that the static internal class itself is a static member of the external class, so the 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 clarified during Java 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 mentioned earlier, all non-static internal class instantiation work depends on the Object Instantiation of its external class.
However, in this Code, the creation of the defined partial internal class "Inner" does not depend on its external class.
This should be because: because the local internal class is defined in a static method, the static method does not hold the object of the class to which it belongs to reference this.
That is to say, local internal classes defined in static methods are subject to the same restrictions as static methods: they cannot access non-static members of any external classes they belong.
The reason why an internal class holds its external Class Object Reference is that it can access all instance members of its external class.
Now that I have been restricted to being unable to access instance members, I naturally do not have to rely on external class objects.
Anonymous internal class
As for the anonymous internal class, we have already mentioned the three reasons for using the internal class.
The Definition Format of anonymous internal classes is usually:
new SuperType(constuction parameters){ //inner class method and data}
For anonymous internal classes, it is simply a short form of internal classes.
Note that for anonymous internal classes, the premise is that the internal class must inherit from an external class or implement an external interface.
As we mentioned above about Java multithreading. The reason why anonymous internal classes can be used is that the defined anonymous internal class implements the Runnable interface.