Initialize a member variable

1. There are two types of member variables

(1) Static variables, also known as class variables. It’s the static modifier.

(2) Instance variables, which are non-static member variables, have no static modifier.

Both types of member variables have different initialization locations and timing.

2. Initialization of static variables

(1) When was the static variable initialized?

Occurs when the class is initialized after it has been loaded.

When a class is used for the first time, if it is not loaded into memory, it is loaded into memory first.

(2) The execution characteristics of initialization

The initialization of a class occurs only once. Perform this operation only once.

If the parent class is not initialized when a subclass is initialized, the parent class is initialized first and then the child class is initialized. If the parent class is initialized, it will not be initialized again.

(3) which code is responsible for the initialization of static variables

① Explicit assignment of static variable declarations

② Statements in static code blocks

class Demo{
    static int a = 1;// Static variables are explicitly assigned
    static int b;

    static{
        // Static code block
        System.out.println("a = " + a);/ / 1
        System.out.println("b = " + b);/ / 0
// System.out.println("c = " + c); // If the syntax check fails, the compiler itself is a program, and its logic will say that this is an error
        System.out.println("c = " + Demo.c);// Can be accessed by "class name.
        a = 2;
        b = 2;
    }

    static int c = 1;

    static{
        System.out.println("c = "+ c); }}Copy the code

(4) Underlying principle: when a class is initialized, it essentially executes the < Clinit >() method

Cl: class class

Init: initialize Indicates initialization

The Clinit () method is not declared manually by the programmer; it is assembled “sequentially” by the compiler from the A and B parts of the code that the programmer wrote above. This means that the above Demo class will become:

class Demo{
    // Static variable declaration
    static int a;
    static int b;
    static int c;

    void clinit(a){
        a = 1;
        System.out.println("a = " + a);/ / 1
        System.out.println("b = " + b);/ / 0
        System.out.println("c = " + Demo.c);// Can be accessed by "class name.", 0
        a = 2;
        b = 2;
        c = 1;
        System.out.println("c = "+ c); }}Copy the code

Instance variable initialization

1. When was the instance variable initialized?

In the new object

2. Execution characteristics of initialization.

(1) Every time a new object is executed

(2) When a subclass instance initializes, it also executes the code associated with the parent instance initializing

The constructor of the subclass must call the constructor of the parent class, which essentially calls the code associated with the initialization of the instance variable in the parent class.

3. Which code is responsible for initializing instance variables

(1) Explicit assignment expression for instance variable declaration

(2) Non-static code blocks

(3) Constructor

① : super(), super(argument list),this(),this(argument list), if the constructor does not write the above code, the default is super().

② the rest of the code in the constructor.

(4) Underlying principles

Each time an object is new, the corresponding () method is actually executed

The <init> method is not declared manually by the programmer, but is assembled from parts (1) (2) (3) above:

ⅰ. Assemble the above (3) ①

ⅱ. Assemble the top (1) and (2), they assemble it in the order they wrote it

ⅲ. Assemble the top (3) ②

Note: If we write more than one constructor for a class, there will be more than one <init> method, i.e. as many constructors, there will be more than one <init> method. They have different parameter lists. When assembling, place (3) ① and (3) ② above in their respective <init> methods, depending on the constructor, and place one copy of each of (1) and (2) above.

class Data{
    int a = 1;// The explicit assignment expression a=1 for instance variable declarations

    {
        // Non-static code blocks, also known as building blocks, are rarely used in real development
        System.out.println("Data non-static code block 1");
        System.out.println("a = " + a);
       // System.out.println("b = " + b); // The compiler is following a "forward reference" when checking the syntax
        System.out.println("b = " + this.b);
        a = 2;
    }

    Data(){
        a = 3;
        b = 3;
        System.out.println("Parametric structure");
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }

    int b = 1;
    {
        // Non-static code block
        System.out.println("Non-static code 2");
        System.out.println("a = " + a);
        System.out.println("b = "+ b); }}class SubData extends Data{{// Non-static code blocks, also known as building blocks, are rarely used in real development
        System.out.println("SubData non-static code block"); }}Copy the code

For example, the Data class above looks like this when assembled

 class Data{
    int a;
    int b;
	void /<init>(){
    super(a);This is the instance initialization code that accesses the default parent, which is Object

    a= 1;
    // Non-static code blocks, also known as building blocks, are rarely used in real development
    System.out.println("Data non-static code block 1");
    System.out.println("a = " + a);
   // System.out.println("b = " + b); // The compiler is following a "forward reference" when checking the syntax
    System.out.println("b = " + this.b);
    a = 2;

    b = 1;

     // Non-static code block
    System.out.println("Non-static code 2");
    System.out.println("a = " + a);
    System.out.println("b = " + b);

    a = 3;
    b = 3;
    System.out.println("Parametric structure");
    System.out.println("a = " + a);
    System.out.println("b = "+ b); }}Copy the code

Execution order

When we first use a class, in a new object, we initialize the class first, and then we initialize the instance. (1) Initialization of the parent class (only performed once)

(2) Subclass initialization (only performed once)

(3) instance initialization code corresponding to the parent class

(4) Instance initialization code corresponding to the subclass

First order:

Superclass static code block

Subclass static code block

The parent class constructs the code block

Parent class constructor

Subclasses construct code blocks

Subclass constructor

polymorphism

1. What is polymorphism?

Literally, in many forms.

In Java, polymorphism means that an object (a variable, to be exact) behaves at compile time

2. How to show polymorphism?

Polymorphic reference:

The type variable name of the parent class = the object of the subclass;Copy the code

At this point, the compile-time type of this variable is inconsistent with the run-time type.

3. Performance results?

When compiled, the variable is compiled according to the parent class type and can only call members such as methods declared in the parent class.

The runtime, which runs according to the subclass type, executes the code that the subclass overrides if the method has been overridden.

4. What are the applications of polymorphism?

Applications of polymorphism lie in:

(1) Polymorphic array

When you declare an array, the type of the element is specified as the superclass type, and the objects that are actually stored are subclass objects.

Person[] array = new Person[5]; array[0] = new Woman(); // Array [0] on the left is of type Person, and on the right is the actual stored object, Woman objectCopy the code

(2) parameters of polymorphism

When a method is declared, the type of the parameter is declared as the superclass type, and when the method is actually called, the argument passed is the object of the subclass.

Public void method(Person Person){... } (Person Person) parameter call: method(new Woman()); The arguments (new Woman ())Copy the code

(3) The return value of polymorphism

The return type of the method is declared as the type of the parent class, and the object of the subclass when the value is actually returned.

Public Person Method (){... return new Woman(); }Copy the code

(4) Conclusion: Polymorphism can make code more flexible and powerful.

Benefits of three basic features of object orientation (encapsulation, inheritance, polymorphism)

1. Encapsulation: safe, hidden details, simple

2. Inheritance: code reusability and code extension ability are improved

3. Polymorphism: Makes code more flexible and easier to use.

Transition up and transition down

1. What is upward and downward transition?

They are all type conversions.

Upcast: Automatically elevates an object/variable type to the type of its parent.

Cast down: Casts an object/variable type to the type of a subclass.

Note: Both up-casting and down-casting are for compile-time types only; runtime types do not change.

Java basic data type conversion:

(1) Automatic type conversion

byte->short->int->long->float->double

​ char->

(2) Cast:

double->float->long->int->short->byte

​ char->

2. Transition upward

(1) Under what circumstances will upward transformation take place?

When a subclass object/subclass type variable is assigned to a variable of the parent class, it is automatically upgraded to a type of the parent class.

(2) What are the problems after the upward transformation?

Through the parent class variable

3. Transition downward

(1) Under what circumstances will downward transformation occur?

When an object of a subclass wants to call a member of the subclass “extended”, the variable that was just cast up must be cast down

(2) What are the problems after downward transformation?

ClassCastException: Type conversion exception may occur

4. How to avoid reporting errors in downward transition?

You can use the instanceof keyword to judge and then transform

5. When does the instanceof keyword judgment return true?

Variable/object instanceof type

The runtime type of the variable/object <= type returns true.

Classification of methods (virtual method and non-virtual method)

Before learning methods, divided into: static method and non-static method.

Now the method is divided into:

1. Non-virtual methods: You can determine which method to call at compile time

A: Static method

B: Private methods, etc

C: Final method

/* Conclusion: For non-virtual methods, just look at compile-time types. * /
public class TestMethod {
    public static void main(String[] args) {
        Base base = new Sub();
        base.method();//base Compile time type is base, run time type is Sub
                     // Call the method overridden by the subclass
                    To avoid these misunderstandings, it is recommended that static methods be called with "class name."

        Sub.method();// Execute the method of the subclass
        Base.method();// Execute the method of the parent class

        Base.test();// Execute test of the parent class
        Sub.test();// Static methods that execute test from the parent class can be inherited from subclasses, but cannot be overridden}}class Base{
    public static void method(a){
        System.out.println("Superclass static method");
    }
    public static void test(a){
        System.out.println("Parent class test static method"); }}class Sub extends Base{

    /* method() is a static method that overrides the parent class */
// @override // We recommend overriding methods with @override. The compiler checks whether the Override method meets its requirements
    public static void method(a){
        System.out.println("Subclass static methods"); }}Copy the code

2. Virtual methods: It is necessary at runtime to determine which method is ultimately executed

In simple terms, virtual methods are methods that can be overridden, and all but virtual methods are non-virtual.

Virtual methods: xx. methods

(1) Static dispatch

Look at the compile-time type of xx. To match the appropriate method in the compile-time type.

The rule of matching: See how well the compile-time types of the arguments match the types of the method parameters

A: Find the compile-time type that best matches the argument = the type of the method parameter

B: Find a compile-time type that is compatible with arguments < the type of the method parameter

(2) Dynamic binding

The runtime looks at the run-time type of xx. In the run-time type to see if the matching method just found was overridden,

If there are overrides, the overridden code is executed, otherwise the code matching the method just found in the compile-time type is executed

Note that static dispatch -> dynamic binding is sequential. Even if there is a method with a higher parameter list matching degree in the subclass, the system will not call the method directly. Instead, the system will first look for a method that is compatible with the parameter type in the parent class, and then see if the method is overridden in the subclass. If overridden, execute the overridden method; If not overridden, it still executes the method in the parent class.

/*

 */
public class TestVirtual {
    public static void main(String[] args) {
        Fu f = new Zi();
        f.method();Foo foo foo foo foo foo foo foo foo foo foo foo foo
                    Method () {// if (f) {// if (f) {// if (f)
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
        BaBa b = new ErZi();
        b.method();//(1) static assignment, the compile-time type of b is BaBa, go to the BaBa class to find method()
                / / (2) the dynamic binding, runtime type b is ErZi, to see whether there is the method ErZi () rewrite, if any, is executed to rewrite, without rewriting, is executed BaBa in the class}}class Fu{
    public void method(a){
        System.out.println("Method method of the parent class"); }}class Zi extends Fu{
    public void method(a){
        System.out.println("Subclass method method"); }}class BaBa{
    public void method(a){
        System.out.println("Dad method method"); }}class ErZi extends BaBa{
    // Not overwrite
    public void method(int a){
        System.out.println("Method method of son class"); }}Copy the code