# Polymorphism and inner class

Posted by DrTrans on Fri, 14 Jan 2022 00:31:25 +0100

# Course notes Day11

• polymorphic
• Inner class
• Memory recycling

## Chapter I polymorphism

#### Section 01 basic theory

Review previous knowledge points

```Object oriented three elements:
(1)encapsulation
(2)inherit
(3)polymorphic
```

What is polymorphism?

```Small poems: Su Shi's Poems "The peak is formed on the side of the ridge, and the distance is different. I don't know the true face of Lushan Mountain. I only live in this mountain."  --- <Title: Xilin wall
You can get different results from different perspectives. The essence is the same.

Life examples: water H2O Three different states: ice and steam

Now there is a class
class Pig extends Animal{ ... }

//Create object 1:
Pig one = new Pig();   //A pig is a pig
//Create underground 2:
Animal two = new Pig(); //Pigs are animals
```

Prerequisites for polymorphism

```(1)A parent-child relationship inherits or implements a relationship
(2)Method rewrite
(3)The left parent right child parent class reference points to the child class object  Animal two = new Pig();
```

#### Section 02 getting started

Case code

Parent class

```//Polymorphic quick start parent class
public class FuLei {
String name = "Wang Jianlin";
int ageFu = 60;

public void say(){
System.out.println("Give you a small goal");
}
public void methodFu(){
System.out.println("I am BABA");
}
}
```

Subclass

```//Polymorphic quick start subclass
public class ZiLei extends FuLei{
String name = "Sephirex Wang";
int ageZi = 30;

public void say(){
System.out.println("None of you have the money");
}
public void methodZi(){
System.out.println("I'm a son");
}
}
```

Test class

```//Test class
public class Test {

public static void main(String[] args) {

//Create objects in polymorphic form. Left father right son
FuLei ooo = new ZiLei();

//Call member variable
System.out.println(ooo.ageFu);  //60
//System.out.println(ooo.ageZi);  // Wrong report
System.out.println(ooo.name);   //Wang Jianlin
//Conclusion 1 of member variables: look at who is on the left of the equal sign, give priority to who is used, and look up if not
//Conclusion 2 of member variables: compile and run on the left
System.out.println("=======");
//Call member method
ooo.methodFu();  //I'm BABA
//ooo.methodZi();  // Wrong report
ooo.say();  //None of you have the money
//Conclusion of member method 1: look at who is on the right of the equal sign, give priority to who is used, and look up if not
//Conclusion 2 of member method: see the left for compilation and the right for operation.
}
}

//Disadvantages of polymorphism: you cannot access subclass specific members (member variables and member methods)
```

design sketch

#### Section 03 two transformations

Basic theory

```1. Upward transformation
A. meaning: Regard the child object as the object of the parent class (the son as the father)
B. give an example: Animal aa = new Pig();  //Pigs are animals

2. Downward transformation
A. meaning: Treat parent objects as son objects (father as son)
B. give an example: Pig  pp = (Pig)aa;   //The animal is a pig
C. application: The disadvantage of polymorphism is that you can't access the special members of subclasses, so you need to use downward transformation to get subclass objects, and then call the special members
```

matters needing attention

```In the process of downward transformation, we should pay attention to exceptions: ClassCastException Type conversion exception.
explain: In the process of upward transformation, what type it was originally, when it was transformed, it should become what type, not his brother.
```

design sketch

How to solve the problem?

Solve the problem of type conversion exception ClassCastException

```//Judge whether the current object comes from the class
if(Object name  instanceof  Class name){
//Code for downward transformation
//Code to call subclass specific members
}
```

Examples

```//Judge whether the object ooo's type comes from the Brother class
if(ooo instanceof Brother){
//Transition downward
Brother bbb = (Brother) ooo;
//Calling subclass specific members
System.out.println(bbb.ageZi);
bbb.methodBro();
}
```

#### Section 04 refers to a deer as a horse

Case code

Animal interface

```//Animal interface
public interface Animal {
//eat
public abstract void eat();
}
```

Horses

```//Horses
public class Ma implements Animal{
@Override
public void eat() {
System.out.println("Horses eat grass...");
}
public void pao(){
System.out.println("Horses run.");
}
}
```

cervidae

```//cervidae
public class Lu implements Animal{
@Override
public void eat() {
System.out.println("Deer eat shit");
}
public void tiao(){
System.out.println("Deer jump.");
}
}
```

Test class

```//Test class
public class Test {

public static void main(String[] args) {
//create object
Ma make = new Ma();
use(make);
//Direct call method (writing method of anonymous object)
use(new Lu());
}

// One method can receive both horse objects and deer objects
// How should the parameters of this method be written?
// Here, you can write a parent class or a parent interface and use polymorphism to pass parameters
public static void use(Animal aa){ //Animal aa  = new Ma();
//Call method [common method call]
aa.eat();
//Call method [if you want to access unique, you should transition down]
//If the aa object comes from the Ma class. Then it is transformed downward into ma
if (aa instanceof Ma){
//Downward transformation
Ma make = (Ma) aa;
//Call subclass specific methods
make.pao();
}
//Judge again if the aa object comes from the Lu class.
if (aa instanceof Lu){
//Downward transformation
Lu luhan = (Lu) aa;
//Call subclass specific methods
luhan.tiao();
}
}
}
```

```1. Improve code scalability
explain: If we say, we define the parameters of the method as the parent class or parent interface. Then you can pass subclasses or implementation classes.
In the past, each subclass needs to be used as a parameter of the method, and many methods may be written.

2. Improve code reusability
Explanation: according to the prerequisite of polymorphism, there is a father-child relationship. Among the advantages of inheritance is to improve the reusability of code.
We give the common code to the parent class. Common methods are handed over to the parent interface, which can improve reusability.
The father defines one copy, which can be used by multiple sons.
```

shortcoming

```Subclass specific members (member variables and member methods) cannot be accessed
If you want access, you need judgment and transformation
```

## Chapter II internal classes

#### Section 01 basic theory

What is an inner class?

```Inner class means that one class contains another class in braces.
be careful: The inclusion relationship here is not an inheritance relationship. (inheritance relationship exists) is A Relationship, subclass can be regarded as parent)

Life examples:
The relationship between the body and the heart is an inclusive relationship. The body contains the heart.
```

What are the classifications of internal classes?

```(1)Member inner class. Independent branch: static member inner class
(2)Local inner class. Independent branch: anonymous inner class
```

Application scenarios of internal classes? When will inner classes be used

```In the past, there were click events in learning interface programming. ( JavaScript I've talked about the click effect) the internal class will be used here.
stay Android It is used more in programming.
Some Java Internal classes will be used in the underlying source code.
```

#### Section 02 member inner class

position

```Write a class in the place of a member variable or member method of a class. (in class, outside method)
```

code

External and internal classes

```//Body (external)
public class Body {

String name = "body";
private int age = 18;

public void exercise(){
System.out.println("Body member method...physical exercise");
}

//-------------------
class Heart{
String name = "heart";
public void jump(){
System.out.println("Heart beat...beng ..");
}
public void show(){
String name = "Hey, hey, hey";
System.out.println(name);  //Hey, hey, hey
System.out.println(this.name); //heart
System.out.println(Body.this.name); //body
System.out.println(Body.this.age);  //18
}
}
//-------------------
}
```

Test class

```//Test class
public class Test {

public static void main(String[] args) {

//If you want to create an object of an inner class, how should you use it?
//The formula is: external within
Body.Heart  bh = new Body().new Heart();
//Calling member variables and member methods
System.out.println(bh.name); //heart
bh.jump();  //Heart beat Bouncing
System.out.println("--------");
bh.show();

}
}
```

#### Section 03 static member inner class

theory

```1. position: A class outside a method in a class. Ensure that it is a member inner class
3. effect: You can call directly with the class name
```

code

External and internal classes

```//External class
@SuppressWarnings("all")
public class Outer {

//Static variable
static String name = "External class";

//Inner class: static inner class
static class Inner {
String name = "Inner class";

public void inNoStatic() {
System.out.println("Inner class...Non static method");
}

public static void inYesStatic() {
System.out.println("Inner class...Static method");
}
}
}
```

Test class

```public class Test {

public static void main(String[] args) {

//Create an object. Accessing non static methods
Outer.Inner one = new Outer.Inner();
//Call method
one.inNoStatic();  //Inner class Non static method

//If you want to call a static method in a static inner class.
Outer.Inner.inYesStatic(); //Inner class Static method
}
}
```

#### Section 04 local internal classes

theory

What is a local internal class?

```1. Location:
Classes defined in methods are called local inner classes.

2. Range:
It can only be used in the method. It cannot be used when the method is out.
```

code

External and internal classes

```//External class: demonstrates a local internal class
@SuppressWarnings("all")
public class Outer {

String name = "External class";

//Member method
public void show() {
//local variable
int age = 18;
//Printout
System.out.println(age);
}

//Member method
public void method() {
//-------------------
class Inner {
String name = "Inner class";

public void say() {
System.out.println("I am a member method of a local inner class");
}
}
//-------------------
//create object
Inner iii = new Inner();
iii.say();
}
}
```

Test class

```//Test class
public class Test {

public static void main(String[] args) {

//Only objects of external classes can be created
Outer ooo = new Outer();
//Call method
ooo.method();
}
}
```

Interview questions

#### Section 05 anonymous inner classes

theory

```1. introduce:
Anonymous inner class refers to an inner class without a name. It is a kind of local inner class.

2. Writing method:
new Class name/Interface name(parameter){
//... method...
};
```

origin

Animal interface

```//Animal interface
@SuppressWarnings("all")
public interface Animal {
//How to eat
public abstract void eat();
}
```

Implementation class

```//Implementation class
@SuppressWarnings("all")
public class Dog implements Animal {
@Override
public void eat() {
System.out.println("Dog eat SHI");
}
}
```

Test class

```//Test class
public class Test {

//Thinking question: can we omit the implementation class (Dog) and not write it?
public static void main(String[] args) {
//Version 1: original usage, create an object that implements a class and call a method
Dog one = new Dog();
one.eat();  //Dogs eat SHI

System.out.println("---------");

//Version 2: polymorphic writing, left parent and right child
Animal two = new Dog();
two.eat(); //Dogs eat SHI

System.out.println("--------");

//Version 3: writing anonymous inner classes
Animal three = new Animal() {
@Override
public void eat() {
System.out.println("Dog eat SHISHI");
}
};
three.eat();
}
}
```

Application scenario

If the parameter of the method is written as an interface, the implementation class of the interface is passed. (anonymous inner class, which is also the implementation class of the interface)

Extension point: the javap class name of the decompiled instruction class

Interface code

```//Define interface
public interface Usb {

//Defining abstract methods: connections
public abstract void connect();
}
```

Test class

```public class Test {

public static void main(String[] args) {
//Direct call method
useUsb(new Usb() {
@Override
public void connect() {
System.out.println("Connect the computer");
}
});
}

//Define a method to use USB interface
public static void useUsb(Usb sb){
//Call method
sb.connect();
}
}

//Summary:
//If the parameters of our method are written as interfaces or classes
//When passing parameters, you write the implementation class or subclass. (it can also be an anonymous inner class)
//In essence, an anonymous inner class is a subclass or implementation class. That is, the use of polymorphism
//Decompile operation: javap class name class
```

## Chapter 3 memory recovery

#### Section 01 memory management

Memory partition map area

Introduction to five regions

1. Program counter

```1. less
Program counter is a small memory space, which is used to indicate the line number of bytecode executed by the current thread.
Simply put, it is to command the program to execute that instruction. (branch, loop, jump, exception)

Java The execution of the virtual machine is performed by multiple threads switching the processor time in turn,
At any one time, a processor will execute only one instruction.
Then, there will be an independent program counter for each thread. The program counters between threads will not be affected and will be stored independently.

3. No abnormality
If the thread is executing a Java This counter records the bytecode address of the executing virtual machine.
If you are performing Native The value record of the counter is null Undefined
At this moment, the memory area is the only one in Java There is nothing in the specification OutOfMemoryError Situation area.
```

2. Virtual machine stack

```1. Thread private
Like the program counter, Java The virtual machine stack is also thread private, and its life cycle is the same as that of thread.

2. describe Java Memory model for method execution
When each method is executed, a stack frame is created at the same time( Stack Frame Stack frame is the basic data structure of method runtime)
It is used to store local variable table, operation stack, dynamic link and method exit information.
The whole process of each method from being called to being executed will correspond to a stack frame in the virtual machine stack, from entering the stack to exiting the stack.

3. abnormal
stay Java In the virtual machine, the following two exceptions are specified.
[1]StackOverflowError   JVM Specifies the maximum depth of the stack. If the execution method exceeds the maximum depth, a stack overflow occurs
[2]OutOfMemoryError     JVM If enough memory cannot be requested during expansion, memory overflow occurs
```

3. Local method stack

```1. by native service
The virtual machine stack is for Java Service
The local method stack is native Method service( native The bottom layer of the method is C\C++Calling the bottom layer of the operating system (such as sound card)

2. abnormal
Like the virtual machine stack, the local method stack throws StackOverflowError and OutOfMemoryError
```

4. Java heap

```1. maximum
For most applications, Java Heap is Java The largest piece of memory managed by the virtual machine

Java A heap is a memory area shared by all threads and is created when the virtual machine starts

3. Store instance
The only purpose of the heap area is to store object instances. Almost all object instances are allocated here.
Another note: in Java As described in the virtual machine specification, all objects and arrays are allocated on the heap,
But with JIT With the development of compiler, the way of allocation on the heap is no longer so absolute.

4. GC
Java The heap is the primary area managed by the garbage collector.
From the perspective of memory recycling, the collector now adopts the generational collection algorithm. stay Java Among the piles, it is subdivided into the Cenozoic generation and the elderly generation.
From the perspective of memory allocation, threads are shared Java The heap can be partitioned into private allocation buffers for multiple threads.
However, regardless of the division, it has nothing to do with the stored content. No matter which area, the stored objects are still object instances.
The purpose of further division is to recycle memory better or allocate memory faster.
```

5. Method area

```The method area stores the data that has been loaded by the virtual machine. It has the following three characteristics:
1. Thread sharing. Method area and Java Like the heap, it is also a memory area shared by various threads
2. Storage data type. Class information, constants, static variables, just in time compiler compiled code
3. Abnormal. If the system defines too many classes, resulting in method area overflow, the virtual machine will also experience memory overflow OutOfMemeryError

The method area can be divided into two areas:
1. Runtime constant pool.
Stored are various literal and symbolic references produced during compilation. After loading, these contents will be stored in the method runtime constant pool.
The runtime constant pool is limited by the memory of the method area. It appears when the constant pool cannot apply for memory space OutOfMemeryError
2. Direct memory, There are four characteristics
A. Data outside the virtual machine (Note: direct memory is not the content of the virtual machine, but the memory outside the virtual machine)
B. Direct distribution (Note: in JDK1.4 Later NIO，Lead in channel Channel buffer Buffer，Can operate on direct memory)
C. Limited by the memory size of the device (Note: limited by the total size of the device, not Java Heap size limit)
D. Exception (Note: it will also occur if the memory capacity is exceeded OutOfMemeryError)
```

#### Section 02 garbage collection

Basic theory

```about Java In terms of benefits: the system helps us control the of garbage collection. (automatically completed by the system and not controlled by the programmer)
about C++ No, his garbage needs to be cleaned manually. (programmers control)
```

An object lifecycle

```1. Just born stage
2. youth
3. Old age
```

Drawing

Mark removal algorithm

explain

```Life examples:
It is equivalent to recording the goods on the shelf first (the goods bought, not bought, empty goods and location records)
Then take the goods that no one buys off the shelf uniformly, which is the early strategy of the garbage collector

working principle:
1. Mark all objects that need to be recycled
2. After marking, all marked objects are recycled uniformly

1. Low efficiency:
Marking and removal are not efficient
2. Memory fragmentation:
After the mark is cleared, a large number of discontinuous memory fragments will be generated.
When the program needs to allocate large objects, it cannot find enough continuous space and has to be triggered in advance GC garbage collector
```

Replication algorithm

explain

```Purpose:
In order to solve the problem of efficiency, replication( copying)The collection algorithm appears

working principle:
1. Divide the memory into two areas of the same size according to the capacity. (e.g A Region and B Area)
2. Each use A In the area, B The area is free.
3. When A After using the area, copy the surviving objects to B In the area, clean it at one time A Content of the area.
4. In this operation, half a block of memory is recycled every time. During the memory allocation process, there is no need to consider the problem of memory fragmentation.

1. Reclaim memory for half a memory area at a time.
2. In the process of allocating memory, there is no need to consider the complexity of memory fragments. Just move the heap top pointer and allocate memory in order.

shortcoming:
1. Waste of space. It's a waste of space to halve the memory.
2. Sometimes it's inefficient. When the survival rate of objects is high, more complex operations are required. At this time, the efficiency is low.
```

Label sorting algorithm

explain

```objective:
In the replication algorithm, if you don't want to waste 50% Additional space is required for allocation guarantee.
In order to cope with the low-end situation that all objects survive in the used memory, so the pension area cannot use this algorithm.

working principle:
1. Mark all objects that need to survive
2. After marking, move the surviving objects to one end
3. Directly clean up the memory outside the boundary
```

Generational collection algorithm

4. Generational collection algorithm

explain

```objective:
Modern commercial virtual machines and garbage collection adopt generational collection algorithms.
This algorithm will divide the memory into several blocks according to the different object life cycle, and adopt the most appropriate collection algorithm according to the characteristics of each region.

Generation collection memory partition:
1. Cenozoic era Young Generation Space  ----> YGC
Nickname: also known as the new area
Features: every time garbage collection, a large number of objects will die, and only a small number will survive.
2. Old age Tenure Generation Space
Nickname: also called nursing home
Features: because the survival rate of the object is high, there is no additional space for guarantee.
Algorithm: Mark clearing algorithm and mark sorting algorithm for recycling
3. Persistent generation  Permanent Space
Nickname: also known as permanent storage
Features: store static files, such as Java Class, method, etc. Persistent generation has no significant impact on garbage collection.
```

Summary: old age process description

1. Objects that survive N times of garbage collection in the younger generation will be put into the older generation.

2. The memory of the old generation is much larger than that of the new generation (about 1:2)

3. When the memory is full in the old age, the Major GC, i.e. Full GC, is triggered, but the frequency is relatively low

Topics: Java