Java learning 2-3_ object-oriented advanced

Three, object-oriented advanced

1.1 Inheritance

"Classification of classes"

Inheritance means that the subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance domain and methods of the parent class, or the subclass inherits methods from the parent class, so that the subclass has the same behavior as the parent class.

Java does not support multiple inheritance, but supports multiple inheritance

1.1.1 Features
  1. The child class has non-private properties and methods of the parent class.
  2. The subclass can have its own attributes and methods, that is, the subclass can extend the parent class
  3. Subclasses can implement the methods of the parent class in their own way.
  4. Java inheritance is single inheritance, but multiple inheritance is possible. Single inheritance means that a subclass can only inherit one parent class. Multiple inheritance means, for example, class A inherits class B, and class B inherits class C, so according to the relationship, class C is class B The parent class of the class. Class B is the parent class of Class A. This is a feature that distinguishes Java inheritance from C++ inheritance.
  5. Improve the coupling between classes (the shortcomings of inheritance, high coupling will cause the closer the connection between the codes, the worse the code independence).
1.1.2 Memory analysis of subclass instantiation

When a subclass is instantiated, it first creates a parent class object in the heap space, and then the subclass has a name in the stack memory. The super in the subclass actually points to the address in the heap space of the parent class. When calling the subclass object accessor, in fact, the object in the parent class is modified through super

Insert picture description here

1.2 super

The super keyword is used to access the members of the parent class, which is used to refer to the parent class of the current object.

Can manipulate the construction method of the parent class, the properties of the parent class, and the methods of the parent class

1.3 Override (override)

  1. The parameter list must be the same
  2. The return type must be the same
  3. The access rights cannot be lower than the access rights of the overridden method in the parent class
  4. The member methods of the parent class can only be overridden by its subclasses
  5. Methods that are declared not static and private cannot be overridden, but can be declared again

Interview questions:

The difference between Override and Overload in Java

  1. Location: Overload: In a class; Override: In a child parent class
  2. Parameter list: overload: must be different; rewrite: must be the same
  3. Return type: overloaded: has nothing to do with the return type; rewrite: the return value type must be consistent
  4. Access authority: overload: has nothing to do with access authority; rewrite: return value type must be consistent
  5. Exception handling: overloading: not related to exceptions; rewriting: exception scope is smaller, but new exceptions cannot be thrown
/*
 * 重写与重载
 */
class Animal {
    
    
    private String name;
    public void call() {
    
    
    }
    //重载,方法名相同,参数不同
    public void call(int time) {
    
    
    }
}

class Dog extends Animal {
    
    
    //重写,方法名与参数相同
    public void call() {
    
    
    }
}

1.4 final

  1. The final keyword declares that the class can be defined as non-inheritable, that is, the final class; or used to modify the method, which cannot be overridden by subclasses.
  2. Instance variables can also be defined as final, and variables defined as final cannot be modified. A method declared as a final class is automatically declared as final, but instance variables are not final
  3. Understanding: The essence of a variable is an "operable storage space". The space location is determined, and the contents inside are uncertain. You can access the "corresponding storage space" through the variable name to manipulate the storage in this "storage space" value.
  4. Generally used to modify constants

1.5 Abstract class

1.5.1 Concept

Abstract classes must use abstract class to declare that there can be no abstract methods in an abstract class. Abstract methods must be written in abstract classes or interfaces.

1.5.2 Abstract methods

A method that is only declared but not implemented is called an abstract method (unimplemented means: there is no "{ }" method body), and the abstract method must be declared using the abstract keyword.

/*
 * 抽象类
 */
abstract class ClassName {
    
    
    public abstract void methodName();//抽象方法
}
1.5.3 Abstract features
  1. Abstract class cannot be instantiated
    • The abstract class itself cannot be instantiated
    • An abstract class must be inherited by subclasses, and the inherited subclass (if not an abstract class) must (overwrite) all abstract methods in the abstract class.
  2. Abstract class can have constructor
    • The process of subclass object instantiation is the same as the inheritance of ordinary classes. The constructor in the parent class is first called (no parameters by default), and then the subclass's own constructor is called.
  3. The difference between abstract class and ordinary class
    • The abstract class must be decorated with public or protected (if it is decorated with private, then the subclass cannot inherit and cannot implement its abstract methods)
    • Abstract classes cannot be instantiated to create objects with the new keyword, but when subclasses are created, the abstract parent class will also be instantiated by JVM
    • If a subclass inherits an abstract class, it must implement all its abstract methods, and the subclass must also be defined as an abstract class

1.6 Interface

1.6.1 Concept

If all methods in a class are abstract methods and all attributes are global constants, then this class can be defined as an interface at this time, the pseudo code is as follows

/*
 * 接口
 */
interface InterfaceName {
    
    
    全局常量;
    抽象方法;
}
1.6.2 Interface-oriented programming ideas

This idea is that the interface is the separation of definition (standards, constraints) and implementation (the principle of separation of name and reality).

advantage:

  1. Reduce program coupling
  2. Easy to extend the program
  3. Conducive to program maintenance
1.6.3 Interface implementations

Multiple interfaces can be implemented

/*
 * 接口实现
 */
class SonClass implements FatherInterface1,FatherInterface3,FatherInterface3 {
    
    

}
1.6.4 Interface inheritance
/*
 * 接口继承
 */
interface A extends B,C {
    
    

}

Note: If you want to use an interface, you must rely on subclasses. The subclass (if it is not an abstract class) should implement all abstract methods in the interface

1.6.5 The difference between interface and abstract class
  1. Abstract classes must be inherited by subclasses, and interfaces must be implemented by classes
  2. Interfaces can only declare abstract methods, abstract methods can be declared in abstract classes, or non-abstract methods can be written
  3. Variables defined in interfaces can only be public static constants, variables in abstract classes are ordinary variables
  4. Abstract classes use inheritance to use, and cannot inherit multiple times. The interface is used by implementation, you can implement more
  5. Abstract classes can contain static methods, but they are not allowed in interfaces (static methods cannot be overridden by subclasses, so static methods cannot be declared in interfaces)
  6. Interface cannot have constructor, but abstract class can have

1.7 Polymorphism

1.7.1 Overview

Polymorphism is multiple manifestations of objects (multiple manifestations)

1.7.2 The manifestation of polymorphism
  1. The polymorphism of objects is conceptually well understood. There are subclasses and parent classes in a class. The subclass is a form of the parent class, and the object polymorphism comes from this.
  2. Method overloading and rewriting are also a kind of polymorphism, but method polymorphism (multiple forms of the same method name). Overloading: the polymorphism of methods in a class; rewriting: the polymorphism of methods in the parent class.
1.7.3 The use of polymorphism: object type conversion

Up-cast: subclass instance becomes parent class instance

Downward transformation: the strength of the parent is forced to become an instance of the child

1.8 instanceof

Binary operators (operators) are also reserved keywords in Java

Function: Its function is to determine whether the object on its left is an instance of the class on its right, and it returns boolean data. Use it to determine whether an object is an instance of a Class class.

boolean result = object instanceof class;

1.9 Object class

The Object class is the parent class (base class) of all classes. If a class does not explicitly inherit a specific class, it will inherit the Object class by default

1.9.1 Object polymorphism

Use Object to receive any reference data type

1.9.2 toString

Object's toString method, returns the memory address of the object, usually rewritten

1.9.3 equals

Indicates whether some other object is "equal to" this object.

Object’s equals method: realizes the most distinguishable equivalence relationship on the object ; that is, for any non-null reference value x and y, if and only if x and y refer to the same object (x == y has the value true ), this method returns true.

5 characteristics when rewriting:

  1. Reflexivity: For any non-empty reference value x, x.equals(x) should return true.
  2. Symmetry: For any non-null reference values ​​x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  3. Transitivity: For any non-null reference value x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  4. Consistency: For any non-null reference value x and y, multiple calls to x.equals(y) always return true or always return false, provided that the information used in the equals comparison on the object is not modified
  5. Non-nullability: For any non-null reference value x, x.equals(null) should return false

1.10 Inner class

In Java, a class can be defined in another class or a method, such a class is called an inner class

1.10.1 Member inner class

The member inner class is the most common inner class, which is defined as being located inside another class

Features: The member inner class can unconditionally access all member attributes and member methods of the outer class (including private members and static members)

Note: When the member inner class has a member variable or method with the same name as the outer class, the hidden phenomenon will occur, that is, the members of the member inner class are accessed by default. If you want to access a member of the same name of an external class, you need to pass:

OutClass.this.value
OutClass.this.mathod()

External use member internal class

Outter outter = new Outter();
Outter.Inner inner = outter.new Inner();
1.10.2 Local inner class

A local inner class is a class defined in a method or a scope. The difference between it and a member inner class is that the access of the local inner class is limited to the method or the scope

/**
 * 内部类
 */
class Person {
    
    
    public Person() {
    
    
    }

    //成员内部类
    class Man {
    
    
        public Man(){
    
    
        }

        public People getPerson() {
    
    
            //局部内部类
            class Student extends People {
    
    
                int age = 0;
            }
            return new Student();
        }
    }
}

Note: Local inner classes cannot have public, protected, private and static modifiers

1.10.3 Anonymous inner class

The pseudo code is as follows

new 父类构造器(参数列表)|实现接口(){
    
    
	//匿名内部类的类体部分
}

To use anonymous inner classes, we must inherit from a parent class or implement an interface. Of course, we can only inherit from a parent class or implement an interface. At the same time, it also has no class keyword, because the anonymous inner class directly uses new to generate an object reference, implicit reference

note:

  1. When using anonymous inner classes, we must inherit a class or implement an interface, but we cannot have both. At the same time, we can only inherit a class or implement an interface.
  2. Constructors cannot be defined in anonymous inner classes
  3. There can be no static member variables and static methods in the anonymous inner class.
  4. Anonymous inner classes are local inner classes, so all restrictions on local inner classes are also effective for anonymous inner classes
  5. An anonymous inner class cannot be abstract, it must implement all the abstract methods of the inherited class or the implemented interface
  6. Only local variables of final type can be accessed
1.10.4 Static inner class

A static inner class is also a class defined in another class, but a keyword static is added in front of the class.

The static inner class does not need to depend on the outer class object, which is similar to the static member properties of the class, and it cannot use the non-static member variables or methods of the outer class.

/**
 * 内部类
 */
public class Test {
    
    
    public static void main(String[] args) {
    
    
        Outter.Inner inner = new Outter.Inner();
    }
}
class Outter {
    
    
    public Outter() {
    
    
    }
    static class Inner {
    
    
        public Inner() {
    
    
        }
    }
}

1.11 Packaging

There is a design principle in Java "Everything is an object", then some basic data types in Java are completely incompatible with this design idea, because the eight basic data types in Java are not reference data Type, so in order to solve this problem in Java, the packaging class of eight basic data types is introduced

Serial number Basic data type Packaging
1 int Integer
2 char Character
3 float Float
4 double Double
5 boolean Boolean
6 byte Byte
7 short Short
8 long Long

With the above eight types of packaging, the basic data types can be operated in the form of classes. However, the above eight packaging categories are also divided into two major types:

  • Number: Integer, Short, Long, Double, Float, Byte are all subtypes of Number, which means it is a number.
  • Object: Character and Boolean are direct subclasses of Object.
1.11.1 Boxing and unboxing

Turn a basic data type into a packaging class, then such an operation is called a boxing operation.

Turning a packaging class into a basic data type is called an unboxing operation.

JDK1.5, the new Java feature adds automatic boxing and automatic unboxing, and four arithmetic operations and self-increase and self-build operations can be carried out through packaging classes

Float f = 10.3f;//自动装箱
float x = f;//自动拆箱
1.11.2 String conversion

Use the wrapper class to change a string into a specified basic data type, which is generally used to receive input data

1.12 Variable parameters

After defining the parameters in a method, you must pass in the one-to-one corresponding parameters when calling, but after JDK 1.5, a new function is provided, which can automatically pass in any number of parameters as needed, pseudo code:

返回值类型 方法名称(数据类型…参数名称){
    
    
	//参数在方法内部 , 以数组的形式来接收
}

Note: Variable parameters can only appear at the end of the parameter list.

1.13 Recursion

Recursion, in mathematics and computer science, refers to the use of the method itself in the definition of the method. In other words, a recursive algorithm is an algorithm that directly or indirectly calls its own method.

[External link image transfer failed. The source site may have an anti-hotlink mechanism. It is recommended to save the image and upload it directly (img-5kosCd1I-1600674464299) (D:\Employment Training\Study Notes\Java Learning 2-3_Object-Oriented Advanced. assets\image-20200920182740523.png)]

  1. Clear recursive termination conditions
  2. Give the way to deal with the termination of recursion

Use the wrapper class to change a string into a specified basic data type, which is generally used to receive input data

1.12 Variable parameters

After defining the parameters in a method, you must pass in the one-to-one corresponding parameters when calling, but after JDK 1.5, a new function is provided, which can automatically pass in any number of parameters as needed, pseudo code:

返回值类型 方法名称(数据类型…参数名称){
    
    
	//参数在方法内部 , 以数组的形式来接收
}

Note: Variable parameters can only appear at the end of the parameter list.

1.13 Recursion

Recursion, in mathematics and computer science, refers to the use of the method itself in the definition of the method. In other words, a recursive algorithm is an algorithm that directly or indirectly calls its own method.

Insert picture description here

  1. Clear recursive termination conditions
  2. Give the way to deal with the termination of recursion
  3. Extract repetitive logic and reduce the scale of the problem

Guess you like

Origin blog.csdn.net/Sky_Coolssy/article/details/108712052