Java internal class. MD

Source: Internet
Author: User

The Java inner class learns from

The idea of Java programming

Overview

What is an internal class?
Thinking in Java is defined so that the definition of a class is placed inside the definition of another class, which is the inner class.

Declares an inner class
package com.company;public class Parcel {    class Contents {        private int i = 11;        public int value() {            return i;        }    }    class Destination {        private String label;        Destination(String whereTo) {            this.label = whereTo;        }        String readLabel() {            return label;        }    }    public void ship(String dest) {        Contents c = new Contents();        Destination d = new Destination(dest);        System.out.println(d.readLabel());    }}public static void main(String[] args) {    Parcel p = new Parcel();    p.ship("Tasmania");}

The above is a simple internal declaration, and there is no special case, except that the class is defined in a kind of declaration, which is a rather odd notation.

To create an object of an inner class

If you want to exactly point to an inner class, the syntax is: outerclassname.innerclassname
Based on this syntax, let's try to create an object of an inner class:

The compilation errors are reported in this syntax, which is obviously not the correct way, as follows ( exposing methods that instantiate an inner class in an external class ):

public class Parcel {    class Contents {        private int i = 11;        public int value() {            return i;        }    }    class Destination {        private String label;        Destination(String whereTo) {            this.label = whereTo;        }        String readLabel() {            return label;        }    }    //!!注意这里,我们暴露了方法来实例化内部类    public Destination to(String dest) {        return new Destination(dest);    }    public Contents contents() {        return new Contents();    }    public void ship(String dest) {        Contents c = new Contents();        Destination d = new Destination(dest);        System.out.println(d.readLabel());    }}//实例化内部类public static void main(String[] args) {    Parcel p = new Parcel();    Parcel.Destination destination = p.to("BeiJing");}

We know that if we instantiate the inner class correctly, we should also know why the new inner class cannot be instantiated directly through the way:

This is because, in an inner class, you can refer to the members of an external class (which is mentioned later), if the inner column is instantiated directly, the inner class is inaccessible to instance members of the external class, because the outer class is not instantiated.
However, if you want to instantiate the inner class directly, it is not possible, and we will talk about it later 静态内部类 .

Linking to an external class
public class Sequence {private object[] items;    private int next = 0;    public Sequence (int length) {items = new Object[length];        } public void Add (Object item) {if (Next < Items.length) {items[next++] = Item;    }} public Sequenceselector selector () {return new sequenceselector ();        } class Sequenceselector {private int i = 0;        public Boolean end () {return i = = Items.length;        } public Object current () {return items[i];            } public void Next () {if (I < items.length) {i++;    }}}}public static void Main (string[] args) {int length = 10;    Sequence s = new Sequence (length);    for (int i = 0; i < length; i++) {s.add (i);    } sequence.sequenceselector selector = S.selector ();        while (!selector.end ()) {System.out.print (selector.current () + ",");    Selector.next (); }}//Output Structure//0,1, 2,3,4,5,6,7,8,9, 

Above us, we use the inner class to complete the code of a simple iterator pattern, notably, when Selector we use the items object, it is worth noting that this object is not selector itself, but rather a private member of sequence. An inner class can accessor methods and fields of an external class, as if it were owned by itself . With this feature, we can accomplish some very elegant designs, such as the iterator pattern, in some specific cases.

Why an inner class can access an object of an external class

The reason is that when an object of an external class creates an internal object, the inner class secretly captures an application that executes an object of the outer class. We don't have to care about the details, because the compiler has helped us deal with it, so why not use new the keyword to instantiate the non-__ static internal class __ doubts will be solved.

. This and. New.this keywords

If you want to get a reference to an external class in an inner class, you can get it by OuterName.this .

public class Outer {    public void test() {    }    class Inner {        public void foo() {            //Outer.this 获取外部类的引用            Outer.this.test();        }    }}
The. New keyword

If you want to instantiate a reference that must be used with an external class, it is created when we first create an instance of the inner class.

public class Parcel {    class Contents {        private int i = 11;        public int value() {            return i;        }    }    class Destination {        private String label;        Destination(String whereTo) {            this.label = whereTo;        }        String readLabel() {            return label;        }    }    //!!注意这里,我们暴露了方法来实例化内部类    public Destination to(String dest) {        return new Destination(dest);    }}

In the above code, we have to write an open method to create an object of the inner class, but this undoubtedly increases our workload, though not much. There is now a new way to create an instance of an inner class---by .new keyword.

Parcel parcel = new Parcel();Parcel.Destination destination = parcel.new Destination("temp");
Inner classes in methods and scopes

When we want to create a class to help us solve a more complex problem, but at the same time, we do not want this class to be public.

public static void main(String[] args) {    class Person {        private String name;        private String gender;        private int age;        public String getName() {            return name;        }        public void setName(String name) {            this.name = name;        }        public String getGender() {            return gender;        }        public void setGender(String gender) {            this.gender = gender;        }        public int getAge() {            return age;        }        public void setAge(int age) {            this.age = age;        }    }    Person person = new Person();    person.setName("LD");    person.setGender("Male");    person.setAge(20);}

For example, the person class can only be used in the main method and not be accessible in other places.

Anonymous inner class

Because I am mainly doing some Android development, in doing some small demo or not to implement some interface just write a few short lines of code, there is absolutely no need to create a new class to solve, I will use anonymous internal class to solve.

Button openBtn = this.findViewById(R.id.openBtn);openBtn.setOnClickListener(new View.OnClickListener() {    @Override    public void onClick(View v) {            }});
Nested classes

As mentioned above, in order to access the types of external classes, internal classes capture references to external classes. At that time, it was determined that the inner class would not invoke an object of an external class, it could be declared as 嵌套类 . It has the following characteristics:

    • Nested classes do not require objects of their enclosing classes
    • You cannot access a member of a fee static type from a nested class
    • Because there is no reference to the external class, you can instantiate it directly from the new keyword
public class Parcel {    public static class Destination {        private String label;        public Destination(String whereTo) {            label = whereTo;        }        public void readLabel() {            System.out.print(label);        }    }}//因为Destination是嵌套类所以能够直接被实例化public static void main(String[] args) {    Parcel.Destination destination = new Parcel.Destination("Beijing");    destination.readLabel();}

Java internal class. MD

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.