Do you really understand interfaces and internal classes, interfaces

Source: Internet
Author: User

Do you really understand interfaces and internal classes, interfaces
Java Access Controller

Private: can only be accessed by the current class

Protected: can be accessed by classes and any sub-classes of the same package (inside and outside the package)

Default: can be accessed by any inside the package

Public: any class can be accessed.

Can Java overload change the class access control operator?

Yes! However, the access permission can only be increased and cannot be reduced. For example

One m method in a extends B and B is that M supports the following expansion: (private does not support overloading)

Default -- protected

Default -- public

Protected -- public

Interface

Is the interface a class?

It can be seen that the interface and the class belong to the reference data type of the java data type, they are of the same level, and the interface is not a class. Classes are defined by class, while interfaces are defined by inteface.

Can member variables be defined in the interface?

Interface meaning: The interface can be understood as a unified "protocol", and the attributes in the interface also belong to the content in the Protocol. However, the attributes of the interface are public, static, and final.

Features of interface members:
A: member variables can only be constants. Default modifier public static final
B: The member method can only be an abstract method. Default modifier public abstract

Functions in the interface must be public, private, protected,Abstract?

If we add the "public" modifier to an internal interface when defining an interface, no error will be reported, but the compiler will prompt the following:

It means that the "public" modifier is redundant.

So what if we add private and protected?

It can be seen that the internal function of the interface is public by default.

1. If the interface method is private and only the current interface can be accessed, what is the significance.

2. If it is default or protected: Because the interface cannot talk about sub-classes, only the implement relationship exists, and protected cannot be modified. Can I not add any access controllers? The actual compilation will automatically become public without any control operators. (The original intention of the interface design is that everyone can call and access)

Add the abstract field before the interface:

The result is the same as that of adding "public,By default, the function in the interface is an abstract public function. You do not need to add the abstart public keyword.

What are the definitions of public, private, and protected when defining interfaces? We define a class to be modified with these access controllers.

Private and protected cannot be used for the interface:

1. private interfaces can only access themselves, making them meaningless.

2. The protected modifier indicates that only the quilt class and other classes in the same package can be accessed. Compared with default, protected can be accessed by multiple categories: sub-classes outside the package.

For the interface, it does not have any subclass, so protected is not valid for it.

Public interface and default Interface

The default interface can only write one internal implement in the package, but not outside the package.

Internal interface

An internal interface is an interface defined in a class.

Advantages of internal interfaces:

1. A logical grouping of interfaces used in the same place;
2. encapsulation thoughts;
3. nested interfaces can enhance the ease of coding and maintainability;

An example of using internal interfaces in the Java standard library is java. util. Map and Java. util. Map. Entry. Java. util. Map is also used as a namespace. The Entry does not belong to the global scope.

Does the internal interface need to be added with static?

For example, if a Request class is encapsulated for a parameter in the Request background, you must set a listener interface to listen on the Request status and returned results. The configuration structure is as follows:

public class Request {    private ListenerInterface listener;    static public interface ListenerInterface{        void onResult();    }    public void request(){        doResest();        listener.onResult();    }    private void doResest(){    }}

In fact, the interface defined in a class is static by default, So adding a static keyword is redundant. If a class interface can be defined as a non-static type, the interface must be implemented only by an object of an external class on the instance before the external interface is implemented, in the above Code, you need to initialize a Request Object Request = new Request (); then new request. listenerInterface () {void onResut () {}} does not support the separation of interfaces and classes, and does not conform to the Independence idea of interface functions.

Internal class
public class test {    private Object []obj;    private int next = 0 ;    test(int i){        obj = new Object[i];    }    public void addObject(Object j){        obj[next++] = j;    }    int getLength(){        return obj.length;    }    public class inerObject {        private int i=0;        public boolean end(){            return i==obj.length;        }        public Object current(){            if(i>=obj.length)                return null;            else                return obj[i];        }        public Object next(){            if(obj.length==0||i>=obj.length){                System.out.print("i is : "+i+"");                return null;            }            else {                System.out.print("i is : "+i+"");            }                return obj[++i];        }    }    public  static void main(String []args){        test t = new test(10);        for(int i=0;i<t.getLength();i++){            t.addObject(Integer.toString(i));        }        inerObject ir = t.new inerObject();        while(!ir.end()){            System.out.println(ir.next());        }    }}

When constructing an internal class in Main, there must be an external class object, which cannot be instantiated.

InerObject ir = t. new inerObject ();
1. When constructing an internal class object, a reference pointing to its external class object is required. If the compiler cannot access this reference, an error is returned. (Except static)

2. The code above shows that the internal class can access the member variables of the class.
Nested class

If you do not need to associate an internal class object with a peripheral object, you can declare the internal class as static, usually called a nested class.

Functions of Nested classes:

1. From the perspective of scope, the nested class is hidden in the peripheral class. The class name can only be used in the peripheral class (that is, it is used as a member variable of the peripheral class ). If you use this class name outside the scope of the peripheral class, you need to apply a name restriction.

2. From the perspective of access permission, the nested class name has the same access permission rules as the object member name of its peripheral class. You cannot access private member functions of nested class objects or create objects for nested classes in the private section of the peripheral class.

Anonymous internal class

The anonymous internal class is an internal class without a name. Because there is no name, the anonymous internal class can only be used once. It is usually used to simplify code writing, but there are also prerequisites for using an anonymous internal class:

Must inherit a parent class or implement an Interface

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 Demo {    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, it is not difficult to compile it as an independent class? 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 Demo {    public static void main(String[] args) {        Person p = new Person() {            public void eat() {                System.out.println("eat something");            }        };        p.eat();    }}

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.