Inner classes and generics

Posted by xkaix on Mon, 07 Feb 2022 20:03:43 +0100

catalogue

Inner class

1. Internal classification

a. Member inner class

1) Creation of class objects within members

2) Can member inner classes define static properties

3) For external classes, can member inner classes be used in static methods of external classes

b. Static inner class

1) Create a static inner class object

2) Can static inner classes have member variables

3) Can a static inner class access member variables of an outer class

4) Summary of member inner class and static inner class

c. Method inner class

d. Anonymous inner class

concept

Anonymous inner classes inherit a class or implement an interface by default

2. Features

1) Internal classes and external classes can easily access each other's private properties

2) Multiple inheritance curves can be used to save the country

3. Internal class usage methods / rules

4. Design of internal class

generic paradigm

1. Introduction of generics

2. Basic use of generics

Use generics to transform the above point class

3. Generic method

4. Generic interface

1) Sub interfaces still retain generics

5. Generic summary

Inner class

The so-called internal class is to set the definition of class structure inside another class

1. Internal classification

There are four types: member internal class; Static inner class; Method inner class; Anonymous inner class (predecessor of Lambda expression)

eg: there are internal classes everywhere in real life: automobile engine and automobile engine. This class is set inside the automobile class [also belongs to a kind of packaging (protective)]

a. Member inner class

(analogy to member methods: member methods can access static domains, but cannot own static domains (static attributes cannot be defined))

A class defined directly in a class without any modifier (static) is a member internal class - member methods or properties

public class Outter {//External class
    //Engine - private internal class, completely hidden from the outside, only used inside the class
    private class Inner{

    }
}

Internal classes and external classes can easily access each other's private properties

1) Creation of class objects within members

1) Internal creation of external classes: it is no different from using other classes

Internal class name internal class reference=new  Inner class();

2) external creation of external class - premise: the internal class is visible to the outside

External class name.Internal class reference=new  External class().new Inner class();
Outter.Inner inner=new Outter().new Inner();
inner.test();

2) Can member inner classes define static properties

No, the internal class of a member must depend on the external class. If the internal class of a member has a static attribute (static attribute: it can be used without an object), it can be accessed without an external class object, which is contradictory.

3) For external classes, can member inner classes be used in static methods of external classes

That is, can I create an internal class object in the external class main (main method: static method - no object can be used)?

This analogy is equivalent to calling a member variable in a static method, and it must not be invoked. There is no object of the external class in the static method of the external class. How can the object without the external class call the internal class of the member.

b. Static inner class

(analogy to static method: static method can access static domain, but cannot access member domain)

An internal class defined in a class and decorated with static. Static inner classes can be used without relying on external class objects

1) Create a static inner class object

1) Internal of external class

ublic class Outter1 {
    static class Inner{
    }
    public void test(){//External class member method
        Inner inner=new Inner();
    }
    public static void main(String[] args) {//External class static method
        Inner inner=new Inner();
    }
}

Question: why can both external class ordinary methods and static methods create static internal class objects?

Analysis: compared with static variables in a class, static attributes in a class can be used without class objects, so static methods of a class can be called, especially member methods. (it can be adjusted without an object, not to mention an object)

2) External class

External class.Internal class reference=new External class.Inner class();
Outter1.Inner inner=new Outter1.Inner();

Static inner class is an ordinary class, which is just set inside a class.

2) Can static inner classes have member variables

Ordinary classes can define their own member variables. Static internal classes can have member fields, that is, they can have their own member properties, but they can't access the member fields of external classes.

public class Outter1 {
    //The static inner class is an ordinary class, which is just set in outer1
    static class Inner{
        static int num=10;
        int age=1;//Member properties
    }

3) Can a static inner class access member variables of an outer class

No. The member variables of the external class can only be accessed by objects. At this time, the internal class has no external class objects, so it cannot be accessed directly.

4) Summary of member inner class and static inner class

1) The inner class of a member can access the member domain and static domain of the outer class, but cannot own the static domain

2) Member inner classes cannot be used in static methods of outer classes

3) A static internal class can have a member domain, but it cannot directly access the member domain of an external class [it can be accessed through a new external class object], but the static domain can be accessed at will

c. Method inner class

Classes directly defined inside the method are not allowed to use any access modifiers and are completely hidden from the outside [analogously to local variables, this method class is gone]

public class Outter2 {
    public void fun(){
        //The internal class of the method will disappear when the method is out, and no access modifiers and static characters can appear
        class Inner{
            
        }
    }
}

Method inner class cannot define static field. If a formal parameter of a method is used in an internal class of a method, the formal parameter is an implicit final declaration (after JDK8, before JDK8, if a formal parameter is used inside a method, the final declaration must be used). In addition, the usage is the same as that of the inner class of the member.

Analysis: the variable num is not used by Inner. If it is used:

Analysis: error reporting: the internal class of the method uses the formal parameter of the method. The formal parameter num is now an implicit final declaration, and the value cannot be modified

You can execute [i.e. + - and other operations] without modifying the value

d. Anonymous inner class

(predecessor of lambda expression [functional programming])

concept

Anonymous inner class is a special version of the inner class of a method. The class name is not written directly. 99% are used in the method parameter transfer process. The anonymous inner class complies with all the requirements of the inner class of the method, and there are more relevant requirements:

Anonymous inner classes inherit a class or implement an interface by default

Generally, it can be an abstract class or an inheritance class

1) Common method [interface parameter passing without anonymous class]

public class Outter3 {
    public static void fun(IMessage msg){
        msg.printMsg();
    }

    public static void main(String[] args) {
        IMessage msg=new IMessageImpl();
        fun(msg);
    }
}
interface IMessage{
    void printMsg();
}
class IMessageImpl implements IMessage{

    @Override
    public void printMsg() {
        System.out.println("Common usage");
    }
}

2) Use anonymous inner classes

public class Outter3 {
    public static void fun(IMessage msg){
        msg.printMsg();
    }

    public static void main(String[] args) {
        fun(new IMessage() {//Instead of creating an interface, an anonymous inner class is created, but this class implements the IMessage interface. It overrides the printMsg method
            //There are a lot of in the parentheses of fun(). This is an anonymous inner class
            //It is equivalent to creating a class, implementing the IMessage interface and creating the object of this class
            @Override
            public void printMsg() {
                System.out.println("Usage of anonymous inner classes");
            }
        });
    }
}
interface IMessage{
    void printMsg();
}

 

2. Features

1) Internal classes and external classes can easily access each other's private properties

public class Outter {
    private String msg="outter Class msg attribute";
    //-----------------------------------------------------------------------
    private class Inner{
        private int num=10;
        public void test(){
            //Direct access to msg attribute in external class
            System.out.println(msg);
        }
    }
    //----------------------------------------------------------------------
    public void fun(){
        //Access the private properties of the inner class through the object of the inner class
        Inner inner=new Inner();
        //Access the private properties of the Inner class
        System.out.println(inner.num);
        inner.test();
    }

    public static void main(String[] args) {
        Outter outter=new Outter();
        outter.fun();
    }
}

2) Using inner classes can save the country by using curves to realize "multi inheritance"

class A{
     int numA=10;
}
class B{
     int numB=20;
}
public class E {
    class C extends A{ }
    class D extends B{ }
    public void test(){
        C c=new C();
        D d=new D();
        System.out.println(c.numA);
        System.out.println(d.numB);
    }

    public static void main(String[] args) {
        E e=new E();
        e.test();
    }
}

3. Internal class usage methods / rules

1. The creation of the internal class of a member depends on the external class object. Before there is no external class object, the internal class object of the member cannot be created

eg: the heart is an internal class of members. Without a human body, the object of the heart cannot be created directly

2. The internal class is a relatively independent entity, and is not related to the external class

3. Internal classes and external classes can easily access each other's private domains: internal classes can directly access the elements and methods of external classes (including private domains), and external classes must access the elements and methods of internal classes (including private domains) through the objects of internal classes.

Reason: the external class object is hidden in the internal class

⭐⭐

public class Outter {
    private String msg="outter Class msg attribute";
    class Inner{
        private int num=10;
        private String msg="Inner class msg attribute";
        public void test(){
            //Direct access to msg attribute in external class
            //The private member variable msg of the external class is directly accessed here
            //Member variables have to be accessed through objects, but not here. Description the external class object is passed into the internal class by default out. println(msg); [if there is no private String msg = "MSG attribute of internal class", the MSG attribute of external class is printed]
            System.out.println(Outter.this.msg);//Outter.this means that the msg attribute of the external class is explicitly called. Remove the msg attribute of the inner class
            System.out.println(Outter.this);//outter.this is the incoming hidden external class object
        }
    }
    public void fun(){//An internal class object is generated in the fun method
        Inner inner=new Inner();
        inner.test();
    }
    public static void main(String[] args) {
        Outter outter=new Outter();//Externally generated external class objects
        outter.fun();
    }
}

4. Design of internal class

The design of internal classes is not our first choice now. When writing data structure code, such as linked list, Node is a typical internal class design. You can use member internal classes or static internal classes, and hide and encapsulate them externally.

generic paradigm

1. Introduction of generics

Coordinate class Point{
  x
  y
}  

Object is used to receive all types of automatic unpacking boxes with packaging classes. The basic type is automatically boxed and changed to Integer or Double for object to receive.

public class Point {
    private Object x;
    private Object y;

    public Object getX() {
        return x;
    }
    public void setX(Object x) {
        this.x = x;
    }
    public Object getY() {
        return y;
    }
    public void setY(Object y) {
        this.y = y;
    }
    public static void main(String[] args) {
        Point point=new Point();
        //Automatic packing
        point.setX(10.1);
        point.setY(20.2);
        //Automatic unpacking
        double x=(double) point.getX();
        double y=(double) point.getY();
        System.out.println("x="+x+" y="+y);
        Point point1=new Point();
        point1.setX("101 degrees east longitude");
        point1.setY("55 degrees north latitude");
        String x1= (String) point1.getX();
        String y1=(String) point1.getY();
        System.out.println("x1="+x1+" y1="+y1);
    }
}

Hidden risk: at the forced type conversion: at this time, x and y are of the same type. If the types of x and Y entered by the user are different, an error will occur during forced conversion.

Type conversion exception:

When x and y are accidentally set to different types, run-time exceptions (type conversion exceptions) will occur during forced conversion. This error occurs during forced conversion and cannot be found during compilation. - > Generics came into being

2. Basic use of generics

Goalkeeper: check whether the type is correct in the compiler

The so-called genericity means that the specific types of properties or method parameters in the class will not be set during class definition, but the types will be defined when the class is used (when creating objects).

public class MyClass<T> {
    /**
     * <>Declaration of type parameters
     * The T in < > after class declaration is called a type parameter and is used to refer to any type ⭐⭐
     * In fact, this T is just a representative. Anything can be written. It means that value1 and Value2 have no explicit type in the class definition, and the compiler is informed of the type only when it is used.
     * For specification purposes, type parameters are replaced by a single uppercase letter
     * T: Represents any class
     * E: Indicates the meaning of Element or exception
     * K;V: K Used with V: Map(Integer,String)
    */
    T value1;
    T value2;
    }

Analysis: This is equivalent to changing T to Integer type. If other types are used for direct compilation, errors will be reported instead of running. If the types of value1 and value2 do not necessarily want to pass at this time, define multiple type parameters:

Use generics to transform the above point class

/**
 * Generic coordinates
 * At this time, X and y are of the same type, and a type parameter is used (type error can be found during verification)
 */
public class Point<T> {
    private T x;
    private T y;
    public T getX() {
        return x;
    }
    public void setX(T x) {
        this.x = x;
    }
    public T getY() {
        return y;
    }
    public void setY(T y) {
        this.y = y;
    }
    public static void main(String[] args) {
        Point<String> point=new Point<>();
        point.setX("120 degrees east longitude");
        point.setY("20 degrees north latitude");
        String x= point.getX();//No forced rotation is required
        String y= point.getY();
    }
}

1) When the type set when creating the Point object is different from the actual storage type, the compilation will report an error and the program cannot be started. The problem will be exposed during compilation in advance.

2) Generics not only check types at compile time, but also do not require forced type conversion.

3. Generic method

Seeing < >, it means that this is a generic declaration, just as class is a declaration of class and interface is a declaration of interface

T in a generic method is different from t in a class.

Generic methods are always subject to their own type parameters and have nothing to do with the type parameters in the class. In order to avoid confusion, when defining generic methods, try to avoid using the type parameter letters used in the class.

public class MyClass<T,E> {
    //T. E represents two different types of parameters, which can be the same or different in specific use
    T value1;
    E value2;

    /**
     * generic method 
     */
    public <S> S test(S s){
        System.out.println(s);
        return s;
    }
    public static void main(String[] args) {
        MyClass<Integer,String> myClass=new MyClass<>();
        myClass.value1=10;
        myClass.test("wow");
    }
}

⭐⭐

4. Generic interface

public interface INews<T> {
    //The return value is t type T test(T t);
    T getNews(T t);
}

The subclass NewsImpl has two choices when implementing the interface: either keep the generic type or specify the type when defining the subclass

1) Sub interfaces still retain generics

public class NewsImpl<T> implements INews<T>{
    @Override
    public T getNews(T t) {
        return null;
    }
}

2) Explicit type (receive String type)

public class NewsImpl2<String> implements INews<String>{
    @Override
    public String getNews(String string) {
        return null;
    }
}

5. Generic summary

1) See that < T > is a generic declaration. T is called a type parameter. Genericity refers to a way in which the type of parameter or attribute is uncertain when defining a class or method, and can only be determined when it is actually running.

2) Generic methods always rely on their own type parameters and can exist independently of generic classes. A generic method can also be defined in a common class.

3) For generic interfaces, subclasses either continue to retain generics: class messageimpl < T > implements IMessage < T >; Or specify the type of generic type when implementing subclasses, which are ordinary classes.

Topics: Java