Section 1 object oriented Basics

Section 1 object oriented Basics

1, Object oriented thought

1.1 general

   Object oriented( Object Oriented)The concept and application of object-oriented has gone beyond programming and software development. It is a method of understanding and abstracting the real world. It is the product of the development of computer programming technology to a certain stage.

   Object oriented is relative to process oriented. It refers to organizing the relevant data and methods as a whole, modeling the system from a higher level, and being closer to the natural operation mode of things.

Transformation from process oriented to object-oriented thinking:

  • Process oriented focuses on the process of execution, and object-oriented focuses on the objects with functions.

  • Process oriented to object-oriented is the change of programmer's thought from executor to commander.

If you understand this concept directly, it may be more abstract because you lack understanding of the original process oriented development language. Let's take a chestnut:

1.2 three thoughts

Conceptually, object-oriented thinking can be divided into the following three kinds: OOA, OOD and OOP

  1. OOA: Object Oriented Analysis

  2. OOD: Object Oriented Design

  3. OOP: Object Oriented Programming

1.3 three characteristics

  1. Encapsulation: all content is invisible to the outside

  2. Inheritance: inherit other functions and continue to develop

  3. Polymorphism: method overloading itself is a manifestation of polymorphism

2, Classes and objects

2.1 concept and relationship

   Class represents a common product and is a comprehensive feature, while object is a product of personality and an individual feature.

   The class can only be used through the object, and all operations of the object are defined in the class.

Class consists of properties and methods:

  • Attribute: it is equivalent to the characteristics of people one by one

  • Method: it is equivalent to people's behaviors, such as talking, eating, singing and sleeping

2.2 definition format of class

class Class name{
    Member properties
    Member method
}

be careful:

  • Classes must be written in. java files.

  • In a. java file, there can be N classes, but only one public modified class can exist.

  • The file name of the. java file must be exactly the same as the class name modified by public, or an error will be reported.

2.3 properties and methods

Attribute definition format:
    Data type property name;
Format of attribute definition and assignment:
    Data type property name = initialize value;

Method definition format:
    Permission modifier return value type method name(Formal parameter list) {
        //Method body
        return Return value;
    }

2.4 creation and use of objects

If a class wants to operate, it must rely on the object. The definition format of the object is as follows:
    Class name object name = new Class name();

If you want to access properties or methods in a class(Definition of method),You can rely on the following syntax forms:
    Access properties in class: object name.Attribute name;
    Method in calling class: object name.method(Actual parameter list);

Examples are as follows:

/**
 * class Class name{
 *     Member properties;
 *     Membership method;
 * }
 *
 * Classes must be written in. java files.
 * There can be N classes in a. java file, but only one public modified class can exist
 * .java The file name of the file must be exactly the same as the class name decorated by public
 *
 */
public class classobject {
    public static void main(String[] args) {
        //Format for creating objects:
        //Class name object name = new class name ();
        Person p = new Person();
        //Object attribute assignment:
        //Format: object name. Attribute name
        p.name = "Zhang San";
        p.age = 18;
        p.sex = 'male';
        p.say();
        int sum = p.sum(100, 200);
        System.out.println(sum);
    }
}

/**
 * Classes are like drawings
 */
class Person{
    //Attributes - Characteristics
    String name;
    int age;
    char sex;
    //Method behavior
    /**
     * Return value type method name (formal parameter list){
     *     Method body
     *     return Return value;
     * }
     *
     * Call format:
     * Object name. Method name (actual parameter list);
     */
    void say() {
        System.out.println("Introduce yourself, I'm"+name+",My age:"+age+"My gender:"+sex);
    }

    int sum(int x, int y) {
        return x + y;
    }

//    void xxx() {
//        if (true) {
//            //return indicates the end method
//            return;
//        }
//        System.out.println("haha");
//    }
}

public class classobject2 {
    public static void main(String[] args) {
        Book b1 = new Book();
        Book b2 = new Book();
        b1.name = "Trisomy";
        b1.info = "science fiction";
        b2.name = "Ordinary world";
        b2.info = "Documentary novel";
        b1.say();
        b2.say();
    }
}

class Book {
    String name;
    String info;

    void say() {
        System.out.println("title:"+name+",Introduction:"+info);
    }
}

2.5 create object memory analysis

2.5.1 stack

   Java The stack area is small, about 2 M It is characterized by extremely fast access speed.

   Stack storage features: first in and last out

   Reasons for fast storage:

- stack memory: create and release space through "stack pointer". Moving the pointer down will create new memory, and moving up will release these memory

   This method is very fast, second only to PC Register, but in this way of moving, the size and range of the movement must be clear. The clear size and range is to facilitate the movement of the pointer, which is a limitation on data storage. The size of the stored data is fixed, which affects the flexibility of the program.

   Because it is not very flexible, more data is stored in heap memory.

The stored contents are:

   **Data of basic data type**  as well as **Reference to data type** 

   For example:
int a = 10;
Person p = new Person();

10 is stored in stack memory, and the reference p of the object is stored in stack memory.

2.5.2 reactor

The stored contents are: class objects.

Java is a pure object-oriented language, which limits the creation of objects: all class objects are created through the new keyword. The new keyword tells the JVM that it needs to create a new object and open up a new heap memory space.

Advantages: compared with stack memory, when creating objects, you don't have to pay attention to how much storage space needs to be opened up in heap memory or the length of memory occupation.

The release of memory in heap memory is completed by GC (garbage collector).

Rules for garbage collector to reclaim heap memory:

When there is no reference to this object in the stack memory, it will be regarded as garbage and wait for the garbage collector to collect it.

For example:

Person p0 = new Person();
Person p1 = p0;
Person p2 = new Person();

2.5.3 method area

The storage contents are:

  • Class information

  • Static variable

  • constant

  • Member method

The method area contains a special area (constant pool) (which stores members decorated with static)

2.5.4 PC register

The PC register holds the address of the JVM instruction currently executing.

2.5.5 local method stack

Save the address of the native method.

Give me an example:

   In the above code, when creating an object, the reference of the object( b1,b2)It is stored in the stack memory. In addition, a real space is opened in the heap memory to store the attributes of the object, and the methods of the class will be stored in the method area.

   When b2=b1 When, is to b1 The address value of the memory is assigned to b2,that b2 It points to b1,0 in heap memory x124 The content of the location will not be referenced, and it will be deleted later GC Recycling.

3, Construction method

   When an object is created,`Person p = new Person();`stay Person The parenthesis on the right is actually calling the constructor.

3.1 general

Function: used for object initialization (personal understanding is more like Python's _init_() function)

Execution timing: when creating an object, it is called automatically. If it is not written in the class, the parameterless construction method is called by default.

Features: there will be at least one constructor in all Java classes. If there is no explicit writing constructor in a class, the compiler will automatically generate a parameterless constructor without any code in the constructor! But it's best to get into the habit of writing.

Note: if you write any constructor yourself, the compiler will no longer automatically generate parameterless constructors.

3.2 definition format

Defined format:
    It is basically the same as ordinary methods, except that the method name must be the same as the class name, and there is no declaration of return value type!
For example:
    public class Demo3 {
        Person p = new Person();
        p = new Person();
    }
    class Person{
        public Person(){
            System.out.println("This method is called when the object is created");
        }
    }
    
public class constructorfunction {
    public static void main(String[] args) {
        Person2 p1 = new Person2("Zhang San");
        p1.age = 18;
        p1.say();
    }
}

class Person2 {
    
    String name;
    int age;
    
    Person2(String n) {
        name = n;
    }

    void say() {
        System.out.println("To introduce myself, I am:"+name+",My age:"+age);
    }
}

3.3 construction method design

  • It is recommended to customize the parameterless construction method and do not rely on the compiler to avoid errors.

  • When there are non constant member variables in the class, it is recommended to provide two versions of construction methods, one is the nonparametric construction method, and the other is the construction method with all attributes as parameters.

  • When all member variables in the class are constants or have no member variables, it is recommended not to provide any version of construction.

4, Method overload

4.1 concept

   Methods defined in a class are allowed to be overloaded.

Methods that meet the following requirements are called overloads:

  1. The method name is the same;

  2. Parameter list length or parameter list type or parameter type order are different;

  3. Independent of return value type

    Method overloading allows us to complete specific functions by passing different parameters to call methods under different requirements.
    
class Math{
    int sum(double x, int y) {
        return y;
    }

    int sum(int y, double x) {
        return y;
    }

    double sum(double x, double y) {
        return x + y;
    }
}

4.2 overloading of construction method

A class can have multiple construction methods:

The overload of the construction method can be completed if the length or type of the parameter list is different.

Function: the overloading of construction methods allows us to call different methods to complete the initialization of objects under different requirements for creating objects.

public class constructor_overload {
    public static void main(String[] args) {
        Person3 p = new Person3("Zhang San", 18);
        p.say();

        Person3 p2 = new Person3("Li Si");
        p2.say();
    }
}

class Person3{

    Person3(String name2, int age2){
        name = name2;
        age = age2;
    }

    Person3(String name2) {
        name = name2;
    }

    String name;
    int age;

    void say() {
        System.out.println("Self introduction, name:"+name+",Age:"+age);
    }
}

5, Anonymous object

An object without an object name is an anonymous object.

Anonymous objects can only be used once. Because there is no object reference, they will be called garbage and wait to be recycled by GC. Objects used only once can be completed by anonymous objects, which will often be used in future development.

public class Anonymousobject {
    /**
     * Anonymity: no name, which means no reference is created in stack memory, and only space is opened in heap memory
     * After use, the object will be recycled
     */
    public static void main(String[] args) {
//        Math2 m = new Math2();
//        int num = m.sum(100, 200);
//        System.out.println(num);

        int num = new Math2().sum(100, 200);
        System.out.println(num);
    }
}

class Math2{
    int sum(int x, int y) {
        return x + y;
    }
}

Tags: Java OOP

Posted on Tue, 23 Nov 2021 17:19:31 -0500 by ethan.whitt