Java-internal class discussion

Source: Internet
Author: User
Internal class

The inner classes concept was introduced in JDK. In Java, another class can be defined inside a class (or a method or statement block). The latter is called an internal class, sometimes called a nested class (nestedclasses. There is a logical relationship between the internal class and the outer class that encapsulates it. Generally, it is only used to define its class or statement block to implement some non-General functional logic, A complete name must be provided when it is referenced externally. The advantage of introducing internal classes is that the source code can be clearer and class naming conflicts can be reduced, just like the factory's general internal product or process standards, you can use any name without worrying about the same name as the external standard because it is used in a different range. Internal classes are a usable feature because they allow the classes that are logically the same attribute to be combined and control the visibility of one class in another class.

 

Why introduce internal classes

I felt that this internal class was really useless before I checked the website. After I understood it, I knew that Java classes only support single inheritance. For convenience, I introduced the concept of internal classes in the class, internal classes can inherit other classes, so that you can implement multiple inheritance of one class through internal class inheritance.

Reference:

What are the advantages of Java internal classes? Why Internal classes? 1. For a simple example, if you want to implement an interface, but a method in this interface is the same as the name and parameter of a method in the class you have conceived, what should you do? In this case, you can create an internal class to implement this interface. Since all the content of the internal class is accessible to external departments, this can complete all the functions that you can directly implement this interface. 2. The real reason is that the combination of internal classes and interfaces in Java can solve a problem that is often complained by C ++ programmers in Java: there is not much inheritance. In fact, the multi-inheritance design of c ++ is very complicated, and Java can implement multi-inheritance effectively by adding interfaces to internal classes.

 

Internal features

(1): Nested classes (internal classes) can reflect logical subordination. At the same time, other classes can be controlled to make internal classes invisible to the outside.
(2): the scope of member variables of an external class is the entire external class, including Nested classes. However, external classes cannot access private members of Nested classes.
(3): logically related classes can be combined to effectively hide information.
(4): Internal classes can directly access members of external classes. You can use this to implement multi-inheritance!
(5): After compilation, internal classes are also compiled into separate classes, but they are named outclass $ inclass.
 

Member internal class

Pay attention to the code first, and pay attention to the creation of a class in line 2.

Public class Outer {private int size; public class inner {private int counter = 10; Public void dostuff () {size ++ ;}} public static void main (string ARGs []) {outer = new outer (); Inner inner = outer. new inner (); inner. dostuff (); system. out. println (outer. size); system. out. println (inner. counter); // system. out. println (Counter); Compilation error. External classes cannot access private variables of internal classes }}

Basic Rules of member Internal classes
(1): There can be various modifiers and four types of permissions can be defined: static, final, and abstract (this is different from ordinary classes );
(2): If there is a static limitation, it is a class level, otherwise it is an object level. Class-level access can be made directly through external classes; object-level access can only be made from external objects.
(3) internal and external classes cannot have the same name
(4): no static members can be declared in non-static internal classes.
(5): Internal classes can call each other as follows:

Class A {Class B {}// B and C can call each other Class C {}}

When using a method defined in a non-static internal class in another external class, you must first create an external class object and then create an internal class object related to the external class, call the internal class method as follows:

Note that there are two rows: 3rd and 4.

public class Outer {public static void main(String args[]) {Outer2 outer = new Outer2();Outer2.Inner inner = outer.new Inner();inner.dostuff();}}class Outer2 {private int size;class Inner {public void dostuff() {size++;}}}

The static internal class is equivalent to the static component of its external class. Its object does not have any dependency with the external class object, so you can create it directly. Example:

Pay attention to 3rd and 10 rows.

public class Outer {public static void main(String args[]) {Outer2.Inner inner = new Outer2.Inner();inner.dostuff();}}class Outer2 {private static int size;static class Inner {public void dostuff() {size++;System.out.println("size=" + size);}}}

Because internal classes can directly access the components of their external classes, naming conflicts are also caused when internal classes and external classes have attributes or methods of the same name. Therefore, you must specify the following parameters when calling multiple layers:
Note that error 9th is returned, and the cause is not found.

Public class Outer {private int size; public class inner {private int size; Public void dostuff (INT size) {size ++; // local size; this. size; // the size of the internal class. An error is returned when compiling this line. this. size ++; // size of the external class }}}

 

Local internal class

Local classes are classes defined in code blocks. They are visible only in the code blocks that define them.

The local class has several important features:
(1): only visible in the code block that defines them;
(2): Any local final variable in the code block that defines them can be used;
(3): The local class cannot be static, nor can it define static members.
(4): the local class cannot be modified with public, private, or protected. The default class can only be used.
(5): The local class can be abstract.

Note that for the first row, the internal class defined in the method is the local internal class.

Public class Outer {public static final int total_number = 5; Public int id = 123; Public void T1 () {final int A = 15; string S = "T1 "; class inner {public void innertest () {system. out. println (total_number); system. out. println (ID); system. out. println (a); // system. out. println (s); invalid. Only the final variable} new inner () of the local method can be accessed (). innertest ();} public static void main (string [] ARGs) {outer T = new outer (); T. t1 ();}}

 

Anonymous internal class

The anonymous internal class is a special form of local internal class, that is, no variable name points to this class instance, and the specific class implementation will be written in this internal class.

Anonymous class rules
(1): No constructor is available for anonymous classes;
(2): The Anonymous class cannot define static members;
(3) Anonymous classes cannot be modified using four types of permissions: static, final, and abstract;
(4): Only one anonymous class instance can be created.

Note that there are some differences between lines 8th and local internal classes.

Public class Outer {public static final int total_number = 5; Public int id = 123; Public void T1 () {final int A = 15; string S = "T1 "; new Aclass () {public void TESTA () {system. out. println (total_number); system. out. println (ID); system. out. println (a); // system. out. println (s); invalid. Only the final variable of the local method can be accessed }}. testa ();} public static void main (string [] ARGs) {outer T = new outer (); T. t1 () ;}} class Aclass {public void TESTA (){}}

 

Summary of internal rules

(1): the class name can only be used in the defined range, unless used in a limited name. The internal class name must be different from the nested class name.
(2): Internal classes can be defined in methods. This rule is relatively simple. It controls the access to the variables of the nested class method. Any variable, whether a local variable or a formal parameter, can be accessed by methods in the internal class if it is marked as final.
(3): Internal classes can use the class variables and instance variables of the nested classes, as well as the local variables in the nested blocks.
(4): Internal classes can be defined as abstract.
(5): Only internal classes can be declared as private or protected to protect them from access from external classes. Access protection does not prevent internal classes from using any member of other classes, as long as one class is nested with another.
(6) An internal class can be implemented as an interface by another internal class.
(7): the internal class automatically declared as static becomes the top class. These internal classes lose the ability to use data or variables in the local scope and other internal classes.
(8): Internal classes cannot declare any static members. Only top-level classes can declare static members. Therefore, an internal class that requires static members must use members from the top-level class.

 

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.