day15_ Packaging and internal

Posted by Dave96 on Mon, 03 Jan 2022 03:05:38 +0100

Packaging

Java provides two type systems, basic types and reference types. Using basic types is efficient. However, when you want to use API s or new features designed only for objects (such as generics), the data of basic data types needs to be wrapped with wrapper classes.

Boxing and UnBoxing

  • Packing: convert the basic data type to a packing class object. Objects that are converted to wrapper classes are designed to use API s and features specifically designed for objects
Integer i1 = new Integer(4);//Using constructor functions
Integer i2 = Integer.valueOf(4);//Use the valueOf method in the wrapper class
  • Unpacking: unpacks packaging objects into basic data types. The conversion to basic data type is generally due to the need for operation. Most operators in Java are designed for basic data types. Comparison, arithmetic, etc
Integer i1 = new Integer(4);
int num1 = i1.intValue();

JDK1. After 5, you can automatically pack and unpack. Note: automatic packing and unpacking can only be realized between the corresponding types.

Integer i = 4;//Automatic packing. Equivalent to integer I = integer valueOf(4);
i = i + 5;//Right of the equal sign: convert the I object to the basic value (automatic unpacking) i.intValue() + 5;
//After the addition operation is completed, box again and convert the basic value into an object.

Summary: what operators can be used for objects (reference data types)?

  • instanceof
  • =: assignment operator
  • ==And! =: It is used to compare addresses, but the types of objects on the left and right sides are consistent or have parent-child class inheritance relationship.
  • For special objects such as strings, "+" is supported to indicate splicing.

Wrapper class cannot be promoted automatically

byte  b = 1;
Integer = b; //error

Some API s for wrapper classes

Convert basic data type to string

int a = 10;
//String str = a;// FALSE
//Mode 1:
String str = a + "";
//Mode 2:
String str = String.valueOf(a);

Convert string to basic data type

String is converted to the corresponding basic type. Except for the Character class, all other wrapper classes have parseXxx static methods, which can convert string parameters to the corresponding basic type, for example:

  • public static int parseInt(String s): converts a string parameter to the corresponding int basic type.

Or convert the string into a wrapper class, and then unpack it automatically to the basic data type

  • public static Integer valueOf(String s): convert the string parameter to the corresponding Integer wrapper class, and then unpack it to the int basic type automatically

Note: if the content of the string parameter cannot be correctly converted to the corresponding basic type, Java. Java. XML will be thrown Lang.numberformatexception exception.

int a = Integer.parseInt("String of integers");
double d = Double.parseDouble("Decimal string");
boolean b = Boolean.parseBoolean("true or false");

int a = Integer.valueOf("String of integers");
double d = Double.valueOf("Decimal string");
boolean b = Boolean.valueOf("true or false");

Max min value of data type

Integer.MAX_VALUE and Integer.MIN_VALUE
Long.MAX_VALUE and Long.MIN_VALUE
Double.MAX_VALUE and Double.MIN_VALUE

Character to case

Character.toUpperCase('x');
Character.toLowerCase('X');

Integer to decimal

Integer.toBinaryString(int i) 
Integer.toHexString(int i)
Integer.toOctalString(int i)

Caching of wrapper class objects

The wrapper class has a buffer. If the buffer is not exceeded, a new object will be created. If the buffer is not exceeded, the object will be shared.

Integer i = 1;
Integer j = 1;
System.out.println(i == j);//true

Integer i = 128;
Integer j = 128;
System.out.println(i == j);//false

Integer i = new Integer(1);//The new is in the heap
Integer j = 1;//This uses a buffered constant object in the method area
System.out.println(i == j);//false

Integer i = new Integer(1);//The new is in the heap
Integer j = new Integer(1);//Another new is in the heap
System.out.println(i == j);//false

Double d1 = 1.0;
Double d2 = 1.0;
System.out.println(d1==d2);//false compare addresses. There are no cached objects. Each one is new

This kind of wrapper objects such as Integer and String are "immutable" objects, that is, once modified, they are new objects, which has nothing to do with arguments.

Junit unit test

Written by the great God, worship: https://blog.csdn.net/weixin_44170221/article/details/106463482

Inner class

What is an inner class?

  • Define a Class A in another class B, which class A is called the inner class and B is called the outer class.

Why declare inner classes?

  • When there is an internal part of a thing that needs a complete structure to describe, and this internal complete structure only provides services for external things and is not used separately in other places, it is best to use internal classes for the whole internal complete structure.
  • Moreover, because the inner class is inside the outer class, it can directly access the private members of the outer class.

What are the forms of inner classes

According to the position of internal class declaration (like the classification of variables), we can be divided into:

  • Member inner class:
    • Static member inner class
    • Non static member inner class
  • Local inner class
    • There are local class names
    • Anonymous inner class

Static inner class

Features of static internal 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 properties, methods, constructors, etc., including static members, in static inner classes
    • You can use the abstract modifier, so it can also be inherited by other classes
    • You can use the final modifier 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 $symbol.
  • Unlike external classes, it allows Four permission modifiers: public, protected, default, and private
    • External classes can only be public or default
  • Static members of external classes can only be used in static inner classes
    • Non static members of external classes cannot be used in static internal classes
  • Outside the external class, you can create objects of static internal classes without using the objects of external classes
  • If a variable in the internal class has the same name as the static member variable of the external class, you can use "external class name." to distinguish
class Outer  {

    int num = 10;
    private static int age = 66;

    static int kk = getNum();

    private static int getNum() {
        System.out.println("66666666");
        return 20;
    }


    public void outerMethod1() {
        System.out.println("this is outerMethod1");
    }

    public static void outerMethod2() {
        System.out.println("this is static outerMethod2");
       // System.out.println(Inner.name);
    }

     static class Inner {

        int num = 66;
        static int age = getNum();

        static String name = "Li Bai";

        public void innerMethod() {

            // System.out.println(num);

            System.out.println(age);
            outerMethod2();
        }

        public static void innerMethod2(){

            int age = 199;
            System.out.println("Local variables:"+age);
            System.out.println("inner:"+Inner.age);
            System.out.println("outer:"+Outer.age);

            System.out.println("this is static innerMethod2");
        }

    }
}

class Animal {
}

class Person {
}

Define test class

import org.junit.Test;

import java.io.OutputStream;

/*
Internal class:
   Define one class inside another

External class: the class outside the internal class is called external class
  External classes can only be modified by public and default

Static inner class:
I Syntax structure:

class External class name{

 //Internal class definition
 [4 kinds of permission modifiers] static [final] class name{


 }
}
II effect
  1.It can break the limitation of java single inheritance

  2.Do more functions in internal classes to serve external classes

  3.You can hide resources

III characteristic:

1.Static inner classes can access the resources of outer classes
     Static properties
     Static method

2.Can an external class use the resources of an internal class
   If it is a static resource, you can directly use the internal class name Resource name
   If it is a non - static resource, it needs to pass the object of the inner class Resource name

3.When there are inner classes in a class
   External class name $internal class name
 */
public class TestStaicClass {

    public static void main(String[] args) {


        Outer.outerMethod2();
       /* Outer o = new Outer();
        o.outerMethod1();*/
       /*//Create an object of an inner class
        Outer.Inner inner = new Outer.Inner();
        inner.innerMethod();
        Outer.Inner.innerMethod2();*/
    }
}

Non static member inner class

Features of non static internal 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 declare static constants.
    • You can use the abstract modifier, so it can also be inherited by other classes
    • You can use the final modifier 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 $symbol.
  • Unlike external classes, it allows Four permission modifiers: public, protected, default, and private
    • External classes can only be 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
  • Outside the external class, you must use the object of the external class to create an object of a non static internal class
    • Therefore, there are two this objects in the method of non static inner class, one is the this object of outer class and the other is the this object of inner class

Code example

public class Outer {

    static int age = 20;
    int num = 30;

    class Inner {

        final static int ll = 90;
        String name = "Li Bai";

        int num  =50;

        public void innerMethod2() {
            int num = 66;
            System.out.println(num);
            System.out.println(this.num);
            System.out.println(Outer.this.num);

        }

        public void innerMethod() {
            System.out.println(age);
            System.out.println(num);
           /* outerMethod1();
            outerMethod2();*/
        }

    }

    class  Inner1{}

    public void outerMethod1() {

        Inner in = new Inner();

        System.out.println(Inner.ll);

        System.out.println(in.name);

        in.innerMethod();
        System.out.println("this is outerMethod1()");
    }

    public static void outerMethod2() {
        System.out.println("this is static outerMethod2()");
    }


}

Define test class

package com.atguigu.innerclass.nostaticclass;
/*
Non static inner class:
  Inner class without static modification

  External class name{

  [Permission modifier] class internal class name{

  }
  }
characteristic:

   1.Non static internal classes can directly use all resources of external classes
        Static and non static resources
        Private and non private resources

   2.The external class uses the resources of the internal class
      1.First create an object of a non static inner class before you can use the resources in the inner class
      2.If it is a static constant in an inner class, it can be used directly
      3.Static methods of external classes cannot use internal class resources

   3.Static methods and static properties cannot exist in a non static inner class
     However, static constants can exist


   4.Several non static inner classes generate several bytecode files
     External class name $internal class name

   5.Each class has a this to refer to the current object
     Gets the name of this external class in the external class this. Attribute name



 */
public class Test {
    public static void main(String[] args) {
       //  Outer outer = new Outer();
       // Outer.Inner inner = outer.new Inner();
       //  System.out.println(outer.num);
        //Use non static inner class objects
        Outer.Inner inner = new Outer ().new Inner();
        inner.innerMethod2();
    }
}

Local inner class

Syntax format:

Characteristics of local internal classes:

  • Like an 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
    • You can declare structures such as properties, methods, constructors, etc. in a local inner class, but do not include static members, unless they are static constants inherited from the parent class
    • You can use the abstract modifier, so it can also be inherited by other inner classes behind the same method
    • You can use the final modifier 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
  • Local inner classes, like local variables, have scope
  • Whether the static or non static members of the external class can be accessed in the local internal class depends on whether the method is static / non static
  • In the local inner class, you can also use the local constant of the method, that is, the local variable declared with final
    • JDK1. After 8, if a local variable is used in the local internal class, it is automatically added final

Example code:

interface Run {
    void run();
}

public class Student {

    public static void main(String[] args) {

        Student s = new Student();
        Run run = s.outerMethod();

        run.run();

    }

    public Run outerMethod() {

        int num = 20;

        class Inner implements Run {
            @Override
            public void run() {
                System.out.println("this is innerMethod\t" + num);
            }
        }
        return new Inner();
    }
}

Define test class

/*
Local internal class: local variable [particularly unimportant]

Syntax structure:
 External class name{
    [Permission modifier] [static] return value type method name (formal parameter list){
        [Modifier] class name{


        }
    }
 }

 be careful:
    1.Local inner classes can only be decorated with default
    2.Local inner classes can be decorated with final /abstract

    3.Local internal classes use the resources of external classes, depending on whether the methods of external classes are static or non-static
       Method is non static, and external class static or non static resources can be used
       The method is static and can directly use the static resources in the external class
    4.After the local internal class is compiled successfully, the corresponding bytecode file will also be generated
       Name of external class $serial number name of internal class
       Person$2Inner.class

    5.Static attributes cannot exist in local inner classes, but static constants can exist

    6.Create an internal class object within a method, and call the methods in the internal class through the internal class object

    7.When a local variable is used in a method of a local inner class, a final (jdk1.8) is automatically added before the variable

 */
public class Person {

    int age = 30;

    static String name = "Li Bai";

    public static void main(String[] args) {

        Person p = new Person();

        p.show();

       // Person.outerMethod();
    }


 public void show() {
        //local variable
        int num = 20;
        class Inner {
            int age = 90;
            final static int num = 99;
            public void innnerMethod() {
               /* System.out.println(age);
                System.out.println(name);*/

                System.out.println("this is innnerMethod()");
            }
        }
      /*  Inner in = new Inner();

        in.innnerMethod();*/
    }

}

Anonymous Inner Class

In the development process, we need to use the object of a subclass of an abstract class or the object of an interface implementation class, and only create one object, and the logic code is not complex. So what did we do?

  1. Write a class that inherits the parent class or implements the interface
  2. Override the method of the parent class or parent interface
  3. Create this subclass or the object that implements the class

Here, considering that this subclass or implementation class is one-time, it is redundant for us to "try our best" to name it. Then we can use anonymous inner classes to avoid the problem of naming classes.

Syntax format

be careful:

Anonymous inner class is a special local inner class, but it has no name. All local inner class restrictions apply to anonymous inner classes. For example:

  • Whether non static member variables of external classes can be used in anonymous inner classes depends on whether the method is static
  • In the anonymous inner class, if you need to access the local variable of the current method, the local variable needs to be added with final

Anonymous inner class is a subclass object created. What can this object do?

  • Usage 1: call the method directly from the object of the anonymous inner class

Define interfaces that use objects of anonymous inner classes to call methods directly

package demo01;
// Parent interface
interface A {
    void a();
}

public class Test {
    public static void main(String[] args) {
        //Anonymous Inner Class 
        new A() {
            @Override
            public void a() {
                System.out.println("aaaa");
            }
        }.a();
    }
}

The definition class uses the object of the anonymous inner class to call the method directly

// Parent class
class B{
    public void b(){
        System.out.println("bbbb");
    }
}

public class Test {
    public static void main(String[] args) {
        //Anonymous Inner Class 
        new B() {
            @Override
            public void b() {
                System.out.println("aaaa");
            }
        }.b();
    }
}
  • Usage 2: reference the object of the anonymous inner class through the variable polymorphism of the parent class or parent interface
interface A {
    void a();
}

public class Test {
    public static void main(String[] args) {
        //An object of an anonymous inner class is referenced polymorphically through a variable of a parent class or parent interface
        A obj = new A() {
            @Override
            public void a() {
                System.out.println("aaaa");
            }
        };
        obj.a();
    }
}
  • Usage 3: anonymous internal class objects as arguments
interface A{
    void method();
}
public class Test{
    //As an internal parameter of an anonymous class
    public static void test(A a){
        a.method();
    }

    public static void main(String[] args){
        test(new A(){
            @Override
            public void method() {
                System.out.println("aaaa");
            }

        });
    }
}