java Foundation-Object Oriented (Review)

1. First Identity Object Oriented

1.1, Process-oriented, Object-oriented

1.1.1, Process Oriented

  • The steps are clear and simple, what to do in the first step, and what to do in the second part...
  • Process-oriented is suitable for handling simpler problems

1.1.2. Object-oriented Thought

  • Think about what classifications are needed to solve problems first, then think about these classifications separately.Finally, process-oriented thinking about the details of a classification is carried out.
  • Object-oriented is suitable for complex problems and problems that require collaboration between multiple people.
  • For describing complex things, in order to grasp from a macro perspective and analyze reasonably as a whole, we need to use object-oriented to analyze the whole system.However, specific to micro-operation, it still needs process-oriented thinking to deal with.

1.2. What is Object Oriented

  • Object-Oriented Programming (OOP)

  • Essential: Organize code as classes, and organize (encapsulate) data as objects.

  • abstract

  • Three characteristics

    • encapsulation
    • inherit
    • polymorphic
  • From an epistemological point of view, there are objects before classes.Objects are concrete things and classes are abstract objects.

  • From the code run point of view, there are classes before objects.Classes are templates for objects.

1.3. Relationship between Classes and Objects

  • Class is an abstract data type. It is the overall description/definition of a certain kind of thing, but it cannot represent a specific thing.

    • Animals, plants, mobile phones, computers...
    • Person class, Pet class, Cat class, etc. are all used to describe/define the characteristics and behavior a specific thing should have.
  • Objects are concrete instances of abstract concepts, such as Zhang San's a concrete instance of human beings and his family's dog prosperity is a specific instance of dogs.

2. Creating and initializing objects

  • Use new to create objects.

  • When created using the new keyword, in addition to allocating memory, default initialization of the created object and calls to constructors in the class are also made.

  • Constructors in classes are also called construction methods and must be called when creating objects.It has the following characteristics:

    • Must have the same name as the class
    • No return type and no void can be written
  • A class has a default construction method even if it does not write anything

2.1. Constructors

public class Person {
    //A class has a default parameterless construct even if it does not write anything
    //Define constructors visually
    String name;
    
    //Role: 1. Using the new keyword is essentially a call to the constructor
    //2. Value used to initialize the object
    public Person(){} //Parametric construction
    
    //Parametric constructions 3. Once a parametric construct is defined, a definition must be displayed without a parameter
    public Person(String name){
        this.name=name;
    }
	//Alt+insert Shortcut Insert Construction Method
}

2.2. Memory analysis

//Define a pet class
public class Pet {
    public String name; //Default null
    public int age; 	//Default 0
    //Parametric construction

    public void shout(){
        System.out.println("Gave a call");
    }
}
//Apply Class, Create Call Object
public class Application {
    public static void main(String[] args) {
        
        Pet dog = new Pet();

        dog.name = "Prosperous Money";
        dog.age = 3;
        dog.shout();
    }
}
  • Objects operate by reference type: stack - ->stack

3. Packaging

  • The dew of the dew, the hide of the hide
    • Our program design pursues "high cohesion, low coupling".High cohesion means that the internal data details of a class are self-contained and external interference is not allowed.Low coupling: Expose only a small number of methods for external use.
  • Encapsulation (data hiding)
    • Generally, direct access to the actual representation of data in an object should be prohibited, but accessed through an operational interface, called information hiding.
  • Effect
    • Enhance program security and protect data
    • Hide implementation details of code
    • Unified Interface
    • System Maintainability Increased

4. Inheritance

  • Inheritance is essentially an abstraction of a batch of classes to better model the world.
  • Extends means "extension".The subclass is an extension of the parent class, represented by the keyword extends.
  • Classes in Java have only single inheritance, not multiple inheritance!A class can inherit only one parent class.
  • Inheritance is a relationship between classes, as well as dependencies, combinations, aggregations, and so on.
  • Two classes of inheritance relationship, one is a subclass (derived class), one is a parent class (base class), and the subclass inherits the parent class.
  • There should be a "is a" relationship in the sense between the child and the parent.
//Student class (subclass) inherits human (parent)
public class Student extends Person{ /*Person extends Object*/
    ...
}
  • If a subclass inherits the parent class, it will have all the methods of the parent class, whereas private properties and methods cannot be inherited.
  • In Java, all classes inherit Object classes directly or indirectly by default (Ctrl+H can view class relationships)
  • A class decorated with final cannot be inherited.

4.1,super ,this

1. Sup() calls the parent class's construction method, which must be first
2. super must only appear in methods or constructions of subclasses
3. Sup() and this() cannot call the construction method at the same time, because this must also be written on the first line

  • The difference between super and this: super represents a reference to a parent object and can only be used under inheritance conditions;This calls its own object and can be used without inheritance.
super(); //Hide code, default calls to parent class parameterless construct, write only the first line


4.2. Rewriting methods

1. Override: The method of a subclass must be identical to that of a parent class, and the body of the method must be different.
2. Override is a method override, not an attribute
3. Override methods are only related to non-static methods and are not related to static methods (static methods cannot be overridden)

public class B {
    public static void test(){ //Static method
        System.out.println("B==>test()");
    }
}
public class A extends B{ //inherit
    public static void test(){
        System.out.println("A==>test()");
    }
}
public class Application {
    public static void main(String[] args) {
        //The sum of the method calls depends on the type defined on the left
        A a = new A();
        a.test(); //Print A==>test()

        //References to parent classes point to subclasses, but static methods are not overridden
        B b = new A();
        b.test(); //Print B==>test()
    }
}

Modify A.java, B.java

public class B {
    public void test(){ //Non-static method
        System.out.println("B==>test()");
    }
}
public class A extends B{
    @Override //Override B's Method
    public void test() {
        System.out.println("A==>test()");
    }
}
//References to parent classes point to subclasses
B b = new A(); //Subclasses override parent class methods and execute subclass methods
b.test(); //Printing became A==>test()
/* 
Static methods are methods of classes and non-static methods are methods of objects
 With static, B calls the method of class B because class B is defined by class B
 Without static, b calls the method of the object, while b is the object from class A new, calling the method of A
*/
  • Static methods belong to classes, and non-static methods belong to objects
  • Note:
    1. Method names and parameter lists must be the same
    2. Modifier range can be expanded, not reduced
    3. The range of exceptions thrown can be reduced and not expanded
    4. Methods decorated with static (class, not instance), final (constant method), private (private) cannot be overridden

5. Polymorphism

  • Dynamic compilation: type
  • That is, the same method can behave differently depending on the sender
  • The actual type of an object is determined, but there are many references that can point to it
  • Polymorphic Existence Conditions
    • Inheritance
    • Subclass overrides parent method
    • Parent Reference Points to Subclass Object

Note:

  • Polymorphism is a method polymorphism, no attribute polymorphism
  • Parent and child classes, associated type conversion exception: ClassCastException
  • There are conditions: inheritance relationships, methods need to be overridden, parent references point to subclass objects!

5.1, instanceof, and type conversion

  • Comparing instanceof reference types to determine what type an object is
public static void main(String[] args) {

    // Object > String
    // Objest > Person > Student
    // Objest > Person > Teacher
    Object object = new Student();
	// X instanceof Y, is the object to which the X reference refers a subclass of Y
    System.out.println(object instanceof Student); //true
    System.out.println(object instanceof Person); //true
    System.out.println(object instanceof Teacher); //false
    System.out.println(object instanceof Object); //true
    System.out.println(object instanceof String); //false
	
    //Conversion between types: parent-child (high-low), low can be converted to high
    Person obj = new Syudent(); //Person method only (overrides methods overridden with subclasses)
    (Syudent)obj.go(); //You can use the Student method (Student->go()) after a strong turn
}
  • Type Conversion
  1. Parent references objects pointing to subclasses
  2. Converting subclasses into parent classes and going up will lose some of your original methods
  3. Convert parent to subclass, transition down, cast before calling subclass methods
  4. Convenient method invocation (transformation), less duplicate code, concise.

6,Static

  • Static variables can be accessed directly by the class name, also known as class variables.
  • Static variables (or methods) For classes, all objects (instances) are shared.
  • Static area code is initialized together when loading classes, executed earliest and only once (the first new).
  • Math->Random Numbers:
//Static Import Package
import static java.lang.Math.random;

public class Application {
    public static void main(String[] args) {

        //First kind of random number, no guide
        System.out.println(Math.random()); //0.7562202902634543

        //Second random number, static import package
        System.out.println(random()); //0.5391606223844663
    }
}

7. abstract class

  • Abstract modifies the class as an abstract class, and the method of modification is the abstract method.
  • Classes with abstract methods must be declared abstract.
  • Abstract classes cannot use new to create objects; they are used to inherit subclasses.
  • An abstract method has only a declaration of the method, not an implementation, and its subclasses implement it.
  • A subclass inherits an abstract class and must implement all methods of the abstract class, otherwise it must be declared as an abstract class.
//Abstract abstract class class can only inherit single (interfaces can inherit multiple)
public abstract class Action {

    //Constraint ~Someone helps us achieve it ~
    //An abstract method has only a method name, no method implementation
    public abstract void doSth();

    //1. You cannot create a new abstract class, you can only implement it by subclasses, just as a constraint
    //2. Abstract methods can only appear in abstract classes, which can have common methods
    //3. Abstract classes have constructors and can derive subclasses
    //4. Meaning of abstract classes: Constraints to improve development efficiency.Classes, however, can only inherit singly, so they are less limited
}

8. Interface

  • Common class: only concrete implementation
  • Abstract Class: Both concrete implementations and specifications (abstract methods)
  • Interface: only specification, no method to implement, professional constraints!Separation of constraints from implementations: Interface-oriented programming~
  • Interfaces are specifications, which define the idea of a set of rules, "What are you... What must you do...".
  • Interfaces are essentially constraints, and like human laws, they are well established for everyone to abide by.
//Interface interface, interface must have inheritance class
//Implementation classes (implements can inherit multiple interfaces)
//Multiple Inheritance, Multiple Inheritance through Interfaces
public interface UserService {
    //Defined attributes are constants, default modifies public static final
    public static final int AGE = 99; //Normally not used
    //All defined methods are abstract default public Abstracts
    public abstract void run();
    void add();
    void query();
    void delete();
}

Points of Attention

  • The bold style interface has no construction method and cannot be instantiated
  • Implementation classes must override methods in interfaces
  • Implementing classes implements multiple interfaces

9. Internal Classes

Internal classes are defined within a class, such as class A which defines a class B, then B is the internal class of A, and A is the external class relative to B.

Member internal classes: can manipulate private properties and methods of external classes
Static internal class: static decorated, cannot access private properties of external classes
Local internal classes: classes defined in the methods of external classes
Anonymous Internal Class: Class initialized without a name

Video Learning Address: https://www.bilibili.com/video/BV12J41137hu?p=60

Tags: Java

Posted on Sun, 05 Sep 2021 13:25:54 -0400 by slewis1959