Java learning - interfaces and internal classes

Today's learning contents are summarized as follows:

Interface

Demand: need to fly to Beijing for business
Aircraft, birds and Superman cannot belong to the same genus, but they have the same characteristics: they can fly. Therefore, a new concept called interface is introduced, which can be used to standardize the abstract methods in the interface that must be implemented in the class that implements the interface. An interface can be understood as a contract
Define an interface using the keyword interface

public interface Can fly {
    public void take off();
    public void Cruise flight();
    public void land();
}

The interface cannot be used directly, and there must be a corresponding implementation class

public class Aircraft implements Can fly { //Commonness is expressed by implementing interfaces
    private String name; //Name, which is the attribute of the class. Here, you can define the members of the byte class, which is independent of the interface
    //If the current class is not an abstract class, you must implement all abstract methods in the interface
    @Override
    public void take off() {
    System.out.println("Run hard and fly as soon as you look up");
    }
    @Override
    public void Cruise flight() {
    System.out.println("Burn oil hard...");
    }
    @Override
    public void land() {
    System.out.println("I aim...");
    }
}

Define variables through the interface, and use instances of specific classes to call

Can fly obj = new Aircraft();
obj.take off();
obj.Cruise flight();
obj.land();

The purpose of introducing the interface is to isolate the implementation

public void a business travel(aircraft obj){}
//In this way, the current class and aircraft are coupled. If you need to travel by Superman, you must modify the source code

public void a business travel(Can fly obj){}
//The current class is only coupled with the interface, and any object that implements the interface can be passed in as a parameter

Using interfaces instead of specific classes, you can realize the replacement between multiple specific implementation classes that implement interfaces, such as defining superhumans

What is an interface

In Java, multi inheritance is not directly supported, because there will be uncertainty in the call, so Java improves the multi inheritance mechanism and turns it into a multi implementation in Java. A class can implement multiple interfaces, and an interface can inherit multiple interfaces

interface IA{}
interface IB{}
interface IC extends IA,IB{} //Correct, where the method in IC is equal to IA+IB

class A implements IA,IB{}
IA a=new A();
IB b=new A();
  • Interface is a special abstract class, which can only be modified by abstract or public
  • No constructor method
public interface IA{
    public IA(){} //Syntax error
}
  • No attributes, only constants can be defined
public class Test {
    public static void main(String[] args) {
        System.out.println(IA.name); //Constants can be used directly
        System.out.println(B.name); //Implementation classes can also access constants directly
    }
}

interface IA {
    String name = "yanjun";// Only constants can be defined in the interface, and attributes cannot be defined. The default qualifier is
public static final,Custom qualifiers cannot conflict
}

class B implements IA{}
  • It can contain abstract methods or not
interface IA1 {
}// This interface does not contain any abstract methods

class A1Impl implements IA1 {
}
  • Methods in interfaces can only be modified by public, default, abstract, and static
  • Generally, only abstract methods are defined in the interface
  • The defined method defaults to the exposed abstract method
interface IA2{
    int ee();//The default is public abstract int ee();
    public void pp();//The qualifier of the method can be public, abstract, default,static. The previous public can / / be omitted. If the default public is not written
    public abstract void cc();//Here, abstract can be omitted, and it is abstract by default
    //The special keyword default is introduced into JDK1.8, allowing the default implementation
    public default void dd(){ //The call of this method must have an implementation class
        System.out.println("dddd....");
    }
    //In JDK1.8, it is allowed to define static methods in interfaces
    public static void ff(){ //This static method can call IA2.ff() directly through the interface name
        System.out.println("ffffff");
    }
}

Abstract methods must provide implementations in implementation classes

class A2Impl implements IA2{ //All abstract methods in the interface must be implemented in the implementation class, otherwise the current class can only be an abstract class
    public int ee() {
        return 0;
    }
    public void pp() {
        System.out.println("A2Impl....");
    }
    public void cc() {
        System.out.println("A2Impl.....");
    }
    //Because the dd method has a default implementation in the interface, it can be redefined without redefinition
}
  • You can use the default keyword to provide a default implementation for abstract methods. Methods with a default implementation can be redefined or not redefined in the implementation class

Reason for error: multiple inheritance of classes is not supported in Java. A class can only have one parent class

Interface allows multiple inheritance

A class can implement multiple interfaces while inheriting another class

//Interface allows multiple inheritance
interface IA1{
    public void p1();
}
interface IA2{
    public void p2();
}

interface IC extends IA1,IA2{
    public void p3();
}//You can inherit multiple parent interfaces. At this time, there are actually three abstract methods in IC

//Class is a single root inheritance, and it is not allowed to inherit multiple parent classes

A class is allowed to implement multiple interfaces, but the abstract method of each interface must provide implementation, otherwise it is an abstract class. The provided implementation can also be inheritance

public class A1{
    public void p1(){}
}
public class A2 extends A1 implements IA1,IA2{
    public void p2(){}
}

public abstract class A3 extends A1 implements IA1,IA2{}//Because p2 method is not implemented

The appearance of the interface avoids the limitation of single inheritance. In this way, defining the C interface has all the definitions of A+B. you can use the A and B interfaces and the parent class D to declare the variable type and directly new T. However, in the case of constraints, the compiler system recognizes the type of who declares the variable, which means that only the methods in the identified type can be called, and no other methods can be called

interface A{
    public void p1();
}
interface B{
    public void p2();
}
interface C extends A,B{}

class D{
    public void abc(){}
}
class T extends D implements C{
    public void p1(){}
    public void p2(){}
}

D d=new T();//Only abc method can be called here. If other methods are used, type conversion is required
A a=new T();//Only the method p1 declared in the A interface can be called here
B b=new T();//Only the method p2 declared in the B interface can be called here

Declare the syntax of the interface

Access modifier  interface Interface name{ } It is generally recommended to use adjectives for interface names
  • If the public interface is defined, the rules are consistent with the definition of the public class, and the interface name and file name are required to be consistent
  • External interfaces can only use public and default scope qualifiers; If you define an internal interface, you can use four wide-ranging qualifiers
  • The interface actually provides the same operation interface (method). If it is JDK1.8-version, no method will be implemented. Wait for a class or several classes to implement its methods [all methods in the interface must be abstract]. If JDK1.8+ is used, default is allowed to define the default implementation in the interface, and this implementation allows the override to be redefined in the implementation class
public class Test1 {
    public static void main(String[] args) {
        IA2 a2=new A2Impl();
        a2.pp();
    }
}

interface IA2 {
    default void pp(){
        System.out.println("this is pp....");
        this.ff();
    }
    void ff();
}

class A2Impl implements IA2{
    public void ff() {
        System.out.println("this is ff...");
    }
}

Default restrictions on the use of the default method implementation

public class Test1 {
    public static void main(String[] args) {
        IA2 a2 = new A2Impl();
        a2.pp();
    }
}
interface IA2 {
    default void pp() {
        System.out.println("this is No2 pp....");
    }
}
interface IA3 {
    default void pp(){
        System.out.println("this is No3 pp");
    }
}
class A2Impl implements IA2, IA3 {//If there is a default implementation method in IA2 that is consistent with the method in IA3, you must / / redefine it in the implementation class
    public void pp() {
        IA2.super.pp();//Call the default implementation of pp method in IA2 interface
        IA3.super.pp();
    }
}

  • There are no attributes in the interface, and only constants can be defined. It provides some constants that can be shared by the classes that implement it
  • The interface can give access control characters. The public interface is decorated with public, which can be seen everywhere; If the defined interface has no scope qualifier, it can only be accessed in the same package

Only constants and abstract methods can be defined in the interface

  • Only public constants can be defined in the interface. The attributes in the interface are of public static final type by default, and must be of public static final type
interface IA{
    String name="yanjun";//This is actually a constant definition, not an attribute. Its qualifier is public
static final String name="yanjun",The assignment must be made at the same time as the declaration
} //Static block static{} cannot be defined in an interface

//Constructors cannot be defined in interfaces
  • Only public abstract methods can be defined in the interface, and the default keyword can be used to define method implementation only in JDK1.8+. Methods in the interface are public abstract by default, and must be public abstract. Only in JDK1.8+ can the default keyword be used to define the default implementation of the method, and it is allowed to override the redefinition in the implementation class
  • Interfaces cannot be instantiated and can only be implemented through implementation classes, but can be used to declare the types of variables.
    • Interface variable name =new implementation interface class ();
  • Interface has no constructor
  • Abstract methods in interfaces must provide implementations in non Abstract subclasses, which can be inherited

 

interface IA2 {
    public void pp();
}

class A2 {
    public void pp() {
    }
}

class B2 extends A2 implements IA2 { //The implementation of pp method here is inherited from the parent class
}

A class implements the syntax of the interface

class Class name implements Interface name { }
  • The default modifier of the interface abstract method is public, which must be described on the method header with the public keyword when implementing the interface
interface IA2 {
    void pp();
}

class B2 implements IA2 {
    void pp() { //Syntax error, because the method in IA2 interface is public abstract
    }
}
  • An interface can be implemented by multiple subclasses. A subclass can also implement multiple interfaces

Class implementation interface

  • When a class implements an abstract method of an interface, it must use the same method header public
  • If a class implements multiple interfaces, separate them with commas
  • If a class implements two interfaces that declare the same method, it is shared by multiple interfaces
public class Test1 {
    public static void main(String[] args) {
        IA2 a2=new B2(); a2.pp();
        IA3 a3=new B2(); a3.pp();
        }
    }
interface IA2 {
    void pp();
}
interface IA3{
    void pp();
}
class B2 implements IA2,IA3 {
    public void pp() {
        System.out.println("this is B2.pp()");
    }
}
  • Class can define its own additional members when implementing interfaces, which is also the most common form
public class Test1 {
    public static void main(String[] args) {
        IA2 a2=new B2();
        a2.pp();//Other methods in the B2 implementation class cannot be called directly here. If they need to be called, they should be cast
        ((B2)a2).dd();
    }
}

interface IA2 {
    void pp();
}

class B2 implements IA2 {
    public void pp() {
        System.out.println("this is B2.pp()");
    }

    private int age=100;
    public void pp(int k){
        System.out.println("this is pp(int)");
    }
    public void dd(){
        System.out.println("this is dd()");
    }
}
  • If a class does not fully implement all methods of the interface, it must be defined as an abstract class, and any subclass that inherits the class must implement the interface

Constant in interface

  • Constants can be shared for implementation classes of multiple interfaces
public class Test1 {
    public static void main(String[] args) {
        System.out.println(IA2.PI);//Can be used directly
        A3 a=new A3();
        a.setR(4);
        System.out.println(a.getArea());
    }
}
interface IA2 {
    double PI=3.1415;
}
class A3 implements IA2{ //It can also be used directly in the implementation class
    private double r;
    public double getArea(){
        return PI*r*r;
    }
    public void setR(double r) {
        this.r = r;
    }
}
  • You only need to define and assign values in the interface, and you can't modify them later
  • If you specify the implementation class of the interface in the class, you can use the constant of the interface

An object often has multiple identities

  • A subclass in Java can only inherit one parent class (it cannot be represented)
  • A class in java can implement multiple interfaces. (can be expressed)
class Class name implements Interface 1,Interface 2, ... { }
  • Through the dual mechanism of inheritance and runtime polymorphism, we can define a consistent interface used by many different but related object types
  • Maintain the abstract interface and call the instance of the new class without recompiling
public void a business travel(Can fly obj){ obj.take off(); ...}

//When calling, you can pass in objects of different types
 a business travel(new aircraft()); --- a business travel(new bird());

Special features of the interface

  • A class can only have one parent class!
  • A class can implement multiple interfaces!
  • An interface can inherit multiple interfaces
interface Interface name extends Interface name 1 ,Parent interface name 2 , ... { }

Function of interface

  • Unified access
Interface obj=new Implementation 1(); You can also implement 2, 3, etc
obj Only methods defined in the interface can be called
  • Decoupling can isolate specific implementations through interfaces

Decoupling means that there is no relationship between the user and the implementer. No matter how the implementer changes the implementation, it will not change for users

Similarities and differences between interfaces and abstract classes [3 stars]

  • The same point: they are all extracted from upward
  • difference:
    • Abstract classes need to be inherited, and can only be inherited
    • The interface needs to be implemented and can be implemented more
  • Abstract methods and non abstract methods can be defined in abstract classes, and non abstract methods can be directly used after subclass inheritance
  • Abstract methods and default methods can be defined in the interface. Abstract methods must be implemented by subclasses; JDK1.8+ allows methods in interfaces to have default implementations, which can be used directly in implementation classes, and allows definitions to be overridden
  • The inheritance of abstract classes is the is a relationship, which defines the basic common content of the system
  • The implementation of the interface is like a relationship, which defines the additional functions of the system
  • Only constants can be defined in the interface and must be initialized. Attributes can be defined in abstract classes, which can be initialized directly or not at the time of declaration, and constants can be defined at the same time

All public methods in the interface should be abstract. In JDK1.8+ version, the default implementation of methods can be defined through the default keyword, allowing the definition of static methods, and JDK1.9 can start to define private methods; Abstract classes can have abstract methods or ordinary methods

public class Test1 {
    public static void main(String[] args) {
        IA2.pp();
        A2Impl.pp();

        IA2 a2 = new A2Impl();
        a2.pp();// Syntax error
    }
}

interface IA2 {
    public default void cc(){}
    public static void pp() {
        System.out.println("IA2 static....");
    }
}

class A2Impl implements IA2 {
    public static void pp() {
        System.out.println("A2Impl static..");
    }
}

Define the call specification in the interface category, abstract classes to implement the interface, provide common function parts, and finally implement specific classes to implement special methods

public class Test2 {
    public static void main(String[] args) {
        Fa ff = new Son();
        ff.pp();
    }
}
class Fa {
    public static void pp() {
        System.out.println("Fa static....");
    }
}
class Son extends Fa {
    public static void pp() {
        System.out.println("Son static....");
    }
}

 public void pp(); It is an abstract method in the interface, but if the syntax of public void pp() {} is wrong, it is legal to use public default void pp() {} in JDK1.8+ version

How to use interfaces

Generally, interfaces are used to isolate specific implementations, which can change the interdependence between classes into the dependence of classes on interfaces. For example, the business trip class and the flying things are isolated through the flying interface, so that no matter the business trip class needs to be modified or the flying things need to be modified, they will not affect each other
If there are public methods and special methods in a group of related classes, you can use abstract classes to solidify the public method [algorithm skeleton] in the abstract classes, without the repeated implementation of specific subclasses; However, methods that cannot be implemented in abstract classes can be deferred to subclasses. For example, the sorter BubbleSorter, in which the abstract class BubbleSorter solidifies the bubble sorting algorithm used, and delays the unattainable bigger comparison algorithm to the subclass PigSorter of BubbleSorter. At the same time, there is no need to redefine the sorting algorithm in PigSorter
Best software development practice: first define interface specification calling methods, define public methods after using abstract classes to implement interfaces, and finally define specific subclasses to implement all methods

Usage scenarios of interfaces and abstract classes

From the design level, abstract classes embody the inheritance relationship is a, which mainly describes the dependency relationship or parent-child relationship of classes. The relationship between abstract classes and their derived classes is a typical IS-A relationship, that is, the child is a parent.
Interface can be implemented in many ways, and it does not require that the implementer and interface definitions are consistent in concept, only the implementation
Interface defined contract. It mainly describes the behavior contract between types, and the typical CAN-DO relationship between the interface and its implementation class, that is, the child can do parent.


Why do interfaces need default methods
Adding a default method to the interface does not need to modify the implementation class. The new default method of the interface is directly available in the implementation class.


In addition, pay attention to the conflict of default methods.

Inner class

A class or interface is defined inside another class or interface

public class A1{//External class
    class B1{}//Inner class
    interface C1{}//Internal interface
}

Putting one class definition into another is called "inner class"

  • Classes other than inner classes are called outer classes
  • The name of the inner class must be different from that of the outer class, and there is no requirement between it and other classes
//The full name of the inner class is [outer class name $inner class name]

public class A1 {
    public class A1{} //Syntax error
    class B1{} The syntax is correct, and the default compiled result name is A1$B1.class
}
class B1{}
  • The inner class can access all variables and methods of its outer class
public class A1 {//The scope qualifier of an external class can only be public or default package
    private String name;
    public class B1 { //There are four kinds of scope qualifiers for internal classes
        public void pp() {
            System.out.println(name);
            System.out.println(A1.this.name);//A1.this here is used to represent class A1 objects
            A1.this.name="ffff";
            // System.out.println(this.name); The reason for the error is that this refers to the object of the current class. The current Class B1 / / has no attribute name
            pp();
            A1.this.pp();
        }
    }
    private void pp(){}
}
  • External classes cannot directly access the implementation details of internal classes
public class A1 {
    private String name;
    public class B1 {
        private int age=99;
        public void ff() {
            System.out.println(name);
            System.out.println(A1.this.name);
            A1.this.name="ffff";
        }
        private void dd(){}
    }
    private void pp(){
        B1 b=new B1(); //If you need to access the implementation details of the internal class in the external class, you need to build the internal class object, and then access it through the internal / / class object
        b.ff();
        System.out.println(b.age); //Note: private properties in internal classes can be accessed directly
        b.dd();//Private methods can still be called directly
    }
}
  • There are three modifiers private/protected/static added to the internal analogy with the external class. These three modifiers cannot be used on the external class
  • Non static inner classes cannot have static members
protected class B1 {
    private int age = 99;
    { }//Allow non static code blocks
    private static String password="123456";//Static attributes cannot be included in non static inner classes
    static{ }//Static code blocks are not allowed in non static inner classes
    public B1() {//Allows you to define constructor and destructor methods
    }
    public static void hh(){} //Static methods are not allowed in non static inner classes

Role of inner classes

Inner classes provide better encapsulation
Internal classes can directly access private members of external classes
The external class cannot directly access the members of the internal class. You need to build the internal class object to access it
Anonymous inner classes are suitable for creating classes that are used only once

Internal class related design

  • When analyzing a thing, it is found that the thing describes something else, and this thing is still accessing the content of the described thing

Such as cattle and Corbels
If a thing leaves another thing, it has no meaning. In this case, it is recommended to use internal classes, and other classes are not allowed to visit
ask

  • The internal class can directly access the members in the external class because the internal class holds the reference of the external class, that is, the external class name.this

Internal class classification

In Java, a class can be defined in another class or a method. Such a class is called an inner class. In a broad sense, inner classes generally include these four types: member inner classes, local inner classes, anonymous inner classes, and static inner classes.
The inner class actually has a reference to the outer class, and the reference of the outer class is passed in the constructor.

Non static inner class

Basic grammar

public class A1{
    protected class B1{}//The static inner class is protected static class B1{}
}

Characteristics of non static inner classes:

  • Like other classes, it is just another complete class structure defined in the external class
    • You can inherit the parent class you want to inherit and implement the parent interfaces you want to implement, which has nothing to do with the parent class and parent interface of the external class
    • You can declare properties, methods, constructors and other structures in non static inner classes, but you are not allowed to declare static members, but you can
    • Inherit the static members of the parent class, and you can declare static constants.
    • You can use abstract decoration, so it can also be inherited by other classes
    • final decoration can be used to indicate that it cannot be inherited
    • After compilation, it has its own independent bytecode file, but precedes the internal class name with the external class name and the $symbol.
  • Unlike external classes, it allows Four permission modifiers: public, protected, default, and private
    • External classes only allow public or default
  • You can also use all members of an external class, even private, in a non static inner class
  • Non static inner classes cannot be used in static members of external classes
    • Just as static methods cannot access non static member variables and non static methods of this class
  • The object of non static inner class can be created only through the object of outer class outside the outer class
    • Therefore, there are two this objects in the methods of non static inner classes, one is the this object of the outer class, and the other is the this object of the inner class
  • When creating a non static internal class object, you must first create the corresponding external class object
public class A1 {
    public static void main(String[] args) {
        B1 b = new B1();
        B1.C1 cc = b.new C1(); //The internal class is written as [external class name. Internal class name], otherwise import //com.yan.B1.C1 is required; C1 can be used directly. Whether Class C1 is visible depends on the scope qualifier of Class C1
        System.out.println(cc);
    }
}

class B1 {
    public class C1 {
    }
}
  • In any non static inner class, there cannot be static data, static methods, or another static inner class

 

//syntax error
public class A1{
    public class B1{
        public static String name="yan";//Syntax error, unless Class B1 is a static inner class static class B1{}
        static{}//syntax error
        public static void pp(){}//syntax error
        public static class C1{}//syntax error
    }
}
  • Pay attention to the visibility range limitation of internal classes
  • Access method: directly access the members in the internal class in the external class
class B1 {
    private String pwd;
    private void dd(){}
    protected class C1 {
        private String name;
        private void pp(){
            System.out.println(pwd);//Internal classes can directly access private members in external classes
            
            //Another way of writing B1.this.pwd
            dd();
            //Another writing method is B1.this.dd();
        }
    }
    public void ee(){
        //If you need to access members in an inner class, you must first create an inner class object
        C1 cc=new C1();
        //The built inner class object can access the private members in the inner class
        cc.name="abc";
        cc.pp();
    }
}
  • External class Inner class in=new outer class () New inner class ();
public class A1 {
    public static void main(String[] args) {
        B1 b = new B1();
        B1.C1 cc=b.new C1();//Whether the inner class can be accessed depends on the scope qualifier on the inner class
    }
}

class B1 {
    class C1{}
}
  • in. inner class method ();
public class A1 {
    public static void main(String[] args) {
        B1 b = new B1();
        B1.C1 cc=b.new C1();
        cc.pp(); //Whether the pp method can be accessed depends on the scope qualifier of the pp method
    }
}

class B1 {
    class C1{
        public void pp(){}
    }
}
  • Pay attention to the visibility range limitation of internal classes
class B1 {
    private class C1{//Note that Class C1 can only be used in Class B1, and is not visible in other locations
        public void pp(){}
    }
}

Question:

public class A1 {
    public A1(){
        System.out.println("aaaaa");
    }
    public static void main(String[] args) {
        new A1();//Creating an external class object has nothing to do with the internal class. Creating an external class object does not automatically create an internal class object
    }

    class C1 {
        public C1() {
            System.out.println("dddd");
        }
    }
}

Static inner class

Basic syntax:

public class A1{
    public static class B1{}//Static inner class
}

Characteristics of static inner classes:

  • Like other classes, it is just another complete class structure defined in the external class
    • You can inherit the parent class you want to inherit and implement the parent interfaces you want to implement, which has nothing to do with the parent class and parent interface of the external class
    • You can declare structures such as attributes, methods, and constructors in static inner classes, including static members
    • You can use abstract decoration, so it can also be inherited by other classes
    • final decoration can be used to indicate that it cannot be inherited
    • After compilation, it has its own independent bytecode file, but precedes the internal class name with the external class name and the $symbol.
  • Unlike external classes, it allows Four permission modifiers: public, protected, default, and private
    • External classes only allow public or default
  • Static members of external classes can only be used in static inner classes
    • You cannot use non static members of external classes in static internal classes
  • Objects of static inner classes can be created outside the outer classes without using the objects of the outer classes
  • If a variable in the inner class has the same name as the static member variable of the outer class, you can use "outer class name." to distinguish
  • Static inner classes can have static data, static methods, or another static inner class
class B1 {
    static class C1 {// Static members can only be defined in static inner classes
        private static int age = 123;
        private String pwd="123456";//It is also allowed to define non static members
        static {
            System.out.println("c1 static...");
        }
        public static void pp() {
            System.out.println("c1 static pp...");
        }
        public void ff(){//It is also allowed to define non static members
        }
        static class D1{}
        class E1{}
    }
}

How to use static inner classes

public class A1 {
    public static void main(String[] args) {
        B1.C1 cc = new B1.C1();//You can directly create a static internal class object without building an external class object, but whether it is / / visible depends on the scope qualifier
        B1.C1.pp();//Static members in static inner classes can be accessed directly, but whether they are visible depends on the scope qualifier
        cc.ff();
    }
}

problem

public class A1 {
    public static void main(String[] args) {
        B1.C1 cc = new B1.C1();
    }
}
class B1 {
    private B1() {
        System.out.println("bbbbbb");
    }
    static class C1 {// Static members can only be defined in static inner classes
        public C1() {
            System.out.println("cccccc");
        }
        static {
            System.out.println("c1 static...");
        }
//Output only
//c1 static... Automatically execute after the class is loaded
//cccccc building static internal class objects has nothing to do with external classes, so it is not required to build external class objects first
  • Static inner classes can also have non static data, non static methods, or another non static inner class
  • In static internal classes, non static members of external classes cannot be accessed, which is limited by [static methods cannot directly access non static members] in Java syntax
class B1 {
    private static String name1 = "yan1";
    private double salary = 123.456;
    static class C1 {
        private static int age = 123;
        private String pwd = "abc";
        public static void pp() {
            System.out.println(age);// Static methods can only access static members
            // System.out.println(this.age); This or super are not allowed in static methods
            // System.out.println(pwd);  Syntax error
            System.out.println(name1);// Static members in external classes can be accessed directly in static inner classes
            dd();
            // System.out.println(salary); Syntax error, because static methods can only access static members
        }
        public void fff() {
            System.out.println(this.age);
            System.out.println(pwd);//Non static members in the current class
            System.out.println(name1);// B1.this or this is not allowed It is not allowed to use //b1.this because there is no requirement to build external class objects when building C1 class objects
        // System.out.println(salary); The reason for the error is that there is no requirement to build external class objects when building C1 class objects
            dd();
        // ee();z direct access EE method reports an error. When building C1 class objects, it is not required to build external class objects
        }
    }
    private void ee() {
    }
    private static void dd() {
    }
}

Question 1:

class B1 {
    static class C1 {
    }
}

How to build internal class objects:
B1.C1 cc = new B1.C1();
The following creation method is wrong:
B1 b = new B1();
B1.C1 c = b.new C1();

Question 2:

public class A1 {
    public static void main(String[] args) {
        B1.C1 bcc=new B1.C1();
    }
}

class B1 {
    private static D1 dd=new D1();
    static {
        System.out.println("B1 static....");
    }
    static class C1 {
        private static E1 dd=new E1();
        static {
            System.out.println("C1 static...");
        }
    }
}
//When you execute here, you will find that the static code blocks and static attributes of Class B1 are not processed, so you should understand that the external class is actually an internal class
//A namespace of. When loading the internal class, the external class is not actually loaded -- key point

Local inner class

Internal classes can be defined in a method or a code block

public class A1 {
    private int age = 123;
    public static void main(String[] args) {
        A1 aa = new A1();
    }
    public void pp() {
        Date birth = new Date();
        // B1 bb=new B1(); Syntax error, requiring local inner classes to be defined before use
        class B1 { // Local internal classes can only be used in the {} range. The range qualifier with internal classes is consistent with the temporary variable / /, and only final or abstract can be added
            public void ff() {
                System.out.println(age);
                A1.this.age = 555;// You can directly access members in external classes
                System.out.println(birth);
                // Syntax error. If external temporary variables are used in local internal classes, the external temporary variables must be final, but / / final can be omitted
// birth = new Date(); Modifying addresses for reference types is not allowed, but attributes can be modified
                System.out.println("B1...ff()");
            }
        }
        B1 bb = new B1();
    }
}

Characteristics of local internal classes:

  • Like the external class, it is just another complete class structure defined in a method of the external class
    • You can inherit the parent class you want to inherit and implement the parent interfaces you want to implement, which has nothing to do with the parent class and parent interface of the external class
    • Structures such as attributes, methods, constructors, etc. can be declared in local inner classes, but static members are not included, unless they are inherited from the parent class or static constants
    • It can be decorated with abstract, so it can also be inherited by other inner classes behind the same method
    • final decoration can be used to indicate that it cannot be inherited
    • After compilation, it has its own independent bytecode file, but precedes the internal class name with the external class name, $symbol and number.
      • There are numbers here because there are local inner classes with the same name in different methods in the same outer class
  • Unlike member inner classes, it cannot be preceded by permission modifiers, etc
  • Local inner classes, like local variables, have scopes
  • Whether the static or non static members of the external class can be accessed in the local internal class depends on the method
  • In the local inner class, you can also use the local constant of the method, that is, the local variable declared with final
    • After JDK1.8, if a local variable is used in a local inner class, it is automatically added with final

Question:

public class A1 {
    private int age = 123;
    public static void main(String[] args) {
        A1 aa = new A1();
    }
    public void pp() {
        static class B1 {//Local inner class cannot be static
            static int age = 999;//Static members are not allowed
            static{}
            public static void ff(){}
        }
    }
}

Note: local internal classes need to be defined before use, and cannot be defined after use

Anonymous Inner Class

Anonymous inner class is the short form of inner class

public class A1{
    public void pp(){
        class B1 extends C1{}
    }
}
//Simplified writing
public class A1{
    public void pp(){
        new C1(){};//The writing method of the original named class is class B1 extends C1{} new B1();
    }
}
public class A1 {
    public void pp(){
        new Object(){
            public void ff(){ //If the ff method is not defined in the parent class, it can only be called directly
                System.out.println("anon inner class ... ff");
            }
        }.ff();
    }
    public static void main(String[] args) {
        A1 a1=new A1();
        a1.pp();
    }
}

The following expressions are used more frequently

public class A1 {
    public void pp(){
        Object obj=new Object(){
            @Override//Override methods defined in the parent class
            public String toString() {
                return ("anon inner class ... ff");
            }
            public void dd(){} //Cannot call
        };
        System.out.println(obj.toString());//Call methods that override definitions in anonymous inner classes
    }
}

The premise of anonymous inner class is that it must inherit or implement an external class or interface

new interfacename(){......};
new superclassname(){......};

If there is no parameterless constructor in the parent class, then()There should be corresponding parameters in
public class A1 {
    public void pp(){
        new B1(20){ //Because there is no parameterless constructor in Class B1, parameters must be passed directly
        };
    }
}
class B1{
    private int age;
    public B1(int age){
        this.age=age;
    }
}
  • Anonymous inner class has no constructor because it has no name
  • If this anonymous inner class inherits a parent class that only contains a constructor with parameters, these parameters must be taken when creating it
  • Static members cannot be defined

Usage scenarios of anonymous inner classes

When the method parameter is of interface type and there are no more than three methods in the interface, anonymous inner classes can be used as actual parameters to pass

Restrictions on the use of anonymous inner classes

  • Anonymous inner classes cannot be abstract
  • Anonymous inner classes cannot define constructors, and default constructors similar to parent classes
  • Jdk1.8- local variables that require access to local internal classes and anonymous internal classes must be modified with final. This reality has been cancelled since JDK1.8, but the default is final (cannot be modified)
public void pp() {
    final Date birth = new Date();
    class C1 {
        public void ff() {
            System.out.println(birth);
            birth.setYear(2000);// 3900
            // birth=new Date();  Syntax error
            System.out.println("modify year:" + birth);
        }
    }
    new C1().ff();
}

Attention should be paid to the use of 8 simple types such as int /Integer8 simple types of wrapper classes /String

Usage scenarios and benefits of internal classes

  • Each internal class can inherit the implementation of an interface independently, so whether the external class has inherited a (Interface) implementation or not has no impact on the internal class. Inner classes make the multi inheritance solution complete
  • It is convenient to organize classes with certain logical relationships together and hide them from the outside world
public class cattle{
    private class Corbel{}
}
  • Easy to write event drivers
btn.addActionListener(new ActionListener() { //Add the event handling corresponding to the button
    public void actionPerformed(ActionEvent e) {
        showNewWindow(mainWin);
    }
});
  • Easy to write threaded code

Tags: Java

Posted by flaab on Fri, 05 Aug 2022 02:55:15 +0930