Java study notes 9-internal class summary, study notes 9 --

Source: Internet
Author: User
Tags define local

Java study notes 9-internal class summary, study notes 9 --

Java learning notes series:

Java study note 8-interface Summary

Java study notes 7 -- abstract classes and abstract methods

Java study Note 6-class inheritance, Object class

Java study notes 5-Class Method

Java study note 4-object initialization and collection

Java Study Notes 3-Basics of classes and objects

Java study Note 2 -- data type, array

Java study Note 1-Summary of the development environment Platform

URL: http://www.cnblogs.com/archimedes/p/java-study-note9.html.

Java internal classes include non-static internal classes, static internal classes, local internal classes, and anonymous internal classes.

Commonalities of internal classes:

(1) The internal class is still an independent class. After compilation, the internal class will be compiled into an independent. class file, but it is preceded by the class name and $ symbol of the external class.

(2) Internal classes cannot be accessed in normal mode. An internal class is a member of an external class, so the internal class can freely access the member variables of the external class, whether it is private or not.

(3) When the internal class is declared static, it cannot access the member variables of the external class. In this case, the internal class can only access the static member variables of the external class.

The internal classes and interfaces in java can be combined to 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.

Non-static internal class

When a class acts as a non-static member of another class, this class is a non-static internal class.

It is easy to create a non-static internal class. You only need to define a class so that the class can be used as a non-static member of other classes. The non-static internal class is no different from the member variable or member method. You can also add a modifier to the non-static internal class. The basic syntax for creating a non-static internal class is as follows:

Class OutClass {class InClass {// internal class member} // external class member}

In internal programs, access between external classes and internal classes is often performed. It is easy to access the internal class in the external class. You only need to regard the internal class as a class, create the class object, and use the object to call the members in the internal class.

Programs that access internal classes in external classes-- For example:

Class OutClass {class InClass {// create non-static internal class int I = 5; // internal class member} public void fun () {// InClass in = new InClass (); // create an internal Class Object int I = in. i; // access the internal class member System. out. println ("InClass's var is:" + I) ;}} public class javatest {public static void main (String args []) {OutClass out = new OutClass (); out. fun ();}}

Running result:

InClass's var is: 5

Analysis: in the main method, first create an external class object and then access the member methods of the external class. In the member methods of the outer class, an internal class object is created, and the member variables of the internal class are called using the internal class object to obtain the result. Compile the program to generate three class files: Main class, external class, and internal class. The name of the class file generated by the internal class is OutClass $ InClass. class, which can distinguish the internal class of the internal class.

You can not only access the internal class in the external class, but also access the internal class outside the external class. The basic syntax for accessing an internal class outside the external class is as follows.

OutClass.InClass oi=new OutClass().new InClass();

By using this method, you can create an internal class object and use this internal class object to access members of the internal class. This method is not easy to understand and can be divided into the following two statements:

Wai w = new Wai ();

Wai. Nei wn = w. new Nei ();

This makes it easy to understand. First, create an external class object, and then let the external class object call to create an internal class object.

Program for accessing internal classes outside the external class --For example:

Class OutClass {class InClass {// create non-static internal class int I = 5; // internal class member int j = 6 ;}} public class javatest {public static void main (String args []) {OutClass. inClass oi1 = new OutClass (). new InClass (); OutClass ocClass = new OutClass (); OutClass. inClass oi2 = ocClass. new InClass (); System. out. println ("InClass's var I is:" + oi1. I); System. out. println ("InClass's var j is:" + oi1.j );}}

In the sample code, two methods are used to access the internal class from outside the external class. When you access an internal class outside the external class, you cannot directly create an internal class object, because the internal class is only a member of the external class. Therefore, to create an internal class object, you must first create an external class object, and then create an internal class object as an external class object.

Accessing external classes in internal classes

Accessing external classes in internal classes is like that of all members in the same class accessing each other. This is unlimited, including declaring members as private.

For example:

Class OutClass {int I = 8; // external class member variable class InClass {// create non-static internal class public void fun () {System. out. println ("OutClass's var is:" + I) ;}} public class javatest {public static void main (String args []) {OutClass oc = new OutClass (); // create an external Class Object OutClass. inClass oi = oc. new InClass (); // create an internal Class Object oi. fun (); // call Members in the internal class }}

In the sample code, the internal class defines a fun to access the member variable I in the external class. It can be seen that it is very easy to access the external class from the internal class without adding any content, just like calling between member methods. If the external class also has a member variable I, the value of the member variable of the internal class is obtained. The following code is used to solve this problem:

Class OutClass {int I = 8; // external class member variable class InClass {// create a non-static internal class int I = 9; OutClass oc = new OutClass (); public void fun () {// internal class member System. out. println ("InClass's var is:" + I); System. out. println ("OutClass's var is:" + oc. i) ;}} public class javatest {public static void main (String args []) {OutClass oc = new OutClass (); // create an external class Object OutClass. inClass ic = oc. new InClass (); // creates an internal Class Object ic. fun (); // call Members in the internal class }}

In this program, a member variable of an external class is defined first, and then a member variable of an internal class is defined. The names of these two member variables are the same. For internal direct access, the member variables of the internal class are accessed. To access external class member variables, you must first create an external class object and then use this object to call the external class member variables.

Local internal class

The scope of the local internal class is the same as that of the local variable, and only plays a role in the local class. Therefore, when accessing the local internal class, it can only be within the scope of the local internal class.

For example:

Class OutClass {public void fun () {class InClass {// defines a local internal class int I = 5; // member variable of the local internal class} InClass ic = new InClass (); System. out. println ("InClass's var is:" + ic. i) ;}} public class javatest {public static void main (String args []) {OutClass oc = new OutClass (); oc. fun ();}}

This program defines a local internal class and accesses the local internal class. To access this internal class, you must create an internal class object in the method of the internal class. This is because the internal class appears as a local member and can only be called in the method in which it is located.

Access external class member variables in a local internal class

It is easy to access the member variables of an external class in a local internal class, and you do not need to perform too many operations. In a local internal class, you can directly call the member variables of an external class.

For example:

Class OutClass {int I = 9; // defines a member variable of an external class public void fun () {class InClass {// defines a local internal class public void Infun () {System. out. println ("OutClass's var is:" + I); // access the member variable} InClass ic = new InClass (); // create an internal Class Object ic. infun (); // call the member methods in the internal class} public class javatest {public static void main (String args []) {OutClass oc = new OutClass (); // create an external Class Object oc. fun (); // call Members in the internal class }}

In the sample code, a local internal class is defined, and a method is defined in the local internal class to access the member variables of the external class.

Access Local variables of an external class in a local internal class

Unlike member variables that access external classes, local variables that access external classes and local internal classes in the same part cannot be directly accessed in local internal classes.

For example (the following is an error code ):

Class OutClass {public void OutFun () {int I = 9; class InClass {public void InFun () {System. out. println ("OutClass's var is:" + I); // access the member variable of the external class} InClass ic = new InClass (); // create an internal Class Object ic. inFun (); // call the member methods in the internal class} public class javatest {public static void main (String args []) {OutClass oc = new OutClass (); // create an external Class Object oc. outFun (); // call Members in the internal class }}

Running exception:

Exception in thread "main" java. lang. Error: Unresolved compilation problem:
Cannot refer to a non-final variable I inside an inner class defined in a different method

An error occurs when you run the program. The error message is "access local variable I from the internal class; it must be declared as the final type ". In a local internal class, local variables accessing the external class cannot access common local variables. You must declare the local variables as final.

Local internal classes in static methods

Local internal classes are defined differently in non-static methods and static methods. In the previous example, local internal classes are defined in non-static methods, next we will learn how to define local internal classes in static methods. To access members of an external class, the local internal class defined in the static method must be a static member.

Class OutClass {static int I = 4; public static void OutFun () {// external class member class InClass {public void InFun () {System. out. println ("OutClass's local var is:" + I) ;}} InClass ic = new InClass (); ic. inFun () ;}} public class javatest {public static void main (String args []) {OutClass. outFun ();}}
The static internal class has already learned non-static internal classes. Next we will learn what static internal classes are. A static internal class is the role of a static member in an external class. The form of creating a static internal class is similar to that of creating a non-static internal class, but the internal class must be modified to a static one. Modifying the class using static is impossible in the normal class. The syntax for defining static internal classes is as follows:
Class OutClass {static class InClass {// internal class member} // external class member}

Access static internal classes in external classes

Accessing a static internal class in an external class is the same as accessing a non-static internal class in an external class. You only need to consider this point from the perspective of Inter-member access. For example:

Class OutClass {static class InClass {// create static internal class int I = 5; // internal class member} public void OutFun () {// InClass ic = new InClass (); // create an internal Class Object int ii = ic. i; // access the internal class member System. out. println ("static InClass's var is:" + ii) ;}} public class javatest {public static void main (String args []) {OutClass oc = new OutClass (); // create an external Class Object oc. outFun (); // call Members in the internal class }}

Access to static internal classes in external classes is the same as access to non-static internal classes, but access to static internal classes and non-static internal classes in external classes are no longer the same. Because static internal classes are static members of external classes and static members do not need external class objects, when accessing static internal classes, you do not need to create external class objects.

Note: Because the static internal class is a static member of the external class, the static member does not need an external class object, so outside the external class, when accessing static internal classes, you do not need to create external class objects.

Anonymous internal class

The most difficult of all internal classes is anonymous internal classes. An anonymous internal class is an internal class without a class name. Because there is no name, the anonymous internal class can only be used once. It is usually used to simplify code writing,

However, to use an anonymous internal class, you must inherit a parent class or implement an interface.

Create an anonymous internal class

When creating an anonymous internal class, you will use the knowledge to inherit the parent class or implement interfaces. The anonymous internal class has no name. Therefore, when creating an anonymous internal class, you can create an anonymous internal class object at the same time. The syntax format for creating an anonymous internal class is as follows:

New InFather () {// anonymous internal class };

In the syntax for creating an anonymous internal class, InFather is the class name of the parent class inherited by the anonymous internal class, and an object of the anonymous internal class is created using new. In an anonymous internal class, you can override the methods in the parent class or define your own methods.

Example 1: Do not use anonymous internal classes to implement Abstract METHODS

abstract class Person {    public abstract void eat();} class Child extends Person {    public void eat() {        System.out.println("eat something");    }}public class test {    public static void main(String[] args) {        Person p = new Child();        p.eat();    }}

Running result:

Eat something

We can see that we use Child to inherit the Person class, and then implement an instance of Child to transform it to a reference of the Person class. However, if the Child class is used only once, writing it as an independent class will be very troublesome. At this time, an anonymous internal class is introduced.

Example 2: basic implementation of anonymous internal classes

abstract class Person {    public abstract void eat();}public class test {    public static void main(String[] args) {        Person p = new Person() {            public void eat() {                System.out.println("eat something");            }        };        p.eat();    }}

Running result:

Eat something

We can see that the methods in the abstract class Person are implemented in braces, so that the writing of a class can be omitted, and the anonymous internal class can also be used on the interface.

Instance 3: Use an anonymous internal class on the Interface

interface Person {    public void eat();}public class test {    public static void main(String[] args) {        Person p = new Person() {            public void eat() {                System.out.println("eat something");            }        };        p.eat();    }}

Running result:

Eat something

As shown in the preceding example, as long as a class is abstract or an interface, methods in its subclass can be implemented using anonymous internal classes. The most common scenario is the implementation of multiple threads. To implement multiple threads, you must inherit the Thread class or the Runnable interface.

Example 4: anonymous internal class implementation of the Thread class

public class test {    public static void main(String[] args) {        Thread t = new Thread() {            public void run() {                for (int i = 1; i <= 5; i++) {                    System.out.print(i + " ");                }            }        };        t.start();    }}

Running result:

1 2 3 4 5

Instance 5: anonymous internal class implementation of the Runnable interface

public class test {    public static void main(String[] args) {        Runnable r = new Runnable() {            public void run() {                for (int i = 1; i <= 5; i++) {                    System.out.print(i + " ");                }            }        };        Thread t = new Thread(r);        t.start();    }}

Running result:

1 2 3 4 5

References:

1. http://www.cnblogs.com/nerxious/archive/2013/01/25/2876489.html

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.