Java Foundation Part III_ object-oriented

Posted by patnet2004 on Tue, 08 Mar 2022 19:14:48 +0100

Java object oriented

Process oriented & object oriented

  • Process oriented

The steps are clear and simple. What to do in the first step and what to do in the second step

Process oriented is suitable for dealing with some simple problems

  • object-oriented

    Birds of a feather flock together, which is the thinking mode of classification. When thinking about problems, we will first solve what classifications the problems need, and then think about these classifications separately. Finally, we will think about the details under a certain classification process oriented

    Object oriented is suitable for dealing with complex problems and problems requiring multi person cooperation!

  • For describing complex things, in order to grasp them from the macro and analyze them reasonably as a whole, we need to use object-oriented thinking to analyze the whole system. However, when it comes to micro operation, we still need process-oriented thinking to deal with it

What is object oriented

  • Object oriented programming (OOP)

  • The essence of object-oriented programming is to organize code in the form of class and organize (encapsulate) data in the form of object

  • Abstract: the most important idea of programming

  • Three characteristics:

Encapsulation

Inherit

Polymorphism

  • From the perspective of epistemology, there are objects before classes. Objects are concrete things. Yes, objects are abstract
  • From the perspective of code operation, there are classes before objects, and classes are the template of objects

Relationship between class and object

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

    Animals, plants, mobile phones, computers

    Person class, Pet class, Car class, etc. these classes are used to describe / define the characteristics and behavior of a specific thing

  • Objects are concrete instances of abstract concepts

    Zhang San is a concrete example of man, and Wang CAI in Zhang San's family is a concrete example of dog

    It is a concrete instance rather than an abstract concept that can reflect the characteristics and functions

package com.keke.oop.demo01;

/**
 * @ClassName: Student
 * @Description: Student class
 * @Author: keke
 * @Date: 2021/4/7
 */
public class Student {

    //Properties: Fields
    String name; // Default null
    int age; // Default 0

    //method
    public void study() {
        System.out.println(this.name + "I'm learning");
    }

}
package com.keke.oop.demo01;

/**
 * @ClassName: Application
 * @Description: There should be only one main method in a project
 * @Author: keke
 * @Date: 2021/4/7
 */
public class Application {

    public static void main(String[] args) {

        //Class: abstract, instantiated
        //A student object is a concrete instance of a student class
        Student student = new Student();

        Student xiaoming = new Student();
        Student xiaohong = new Student();

        xiaoming.name = "Xiao Ming";
        xiaoming.age = 3;

        System.out.println(xiaoming.name);
        System.out.println(xiaoming.age);

        xiaohong.name = "Xiao Hong";
        xiaohong.age = 3;

        System.out.println(xiaohong.name);
        System.out.println(xiaohong.age);
    }

}

Creating and initializing objects

  • Create an object using the new keyword

  • When using the new keyword, in addition to allocating memory space, the created object will be initialized by default and the constructor in the class will be called

  • Constructors in classes, also known as construction methods, must be called when creating objects, and constructors have the following two characteristics:

    1. Must be the same as the name of the class

    2. There must be no return type and void cannot be written

  • Constructors must master

    package com.keke.oop.demo02;
    
    /**
     * @ClassName: Person
     * @Description:
     * @Author: keke
     * @Date: 2021/4/7
     */
    public class Person {
    
        String name;
    
        //Even if a class doesn't write anything, it will have a constructor called null parameter constructor. If a constructor is redefined, the null parameter constructor will be overwritten
        //At this time, if you need to construct a method, you must display the definition
        //Construction method: 1 Same as class name 2 no return value
        public Person() {
    
        }
    
        public Person(String name) {
            this.name = name;
        }
    
    }
    
    
    package com.keke.oop.demo02;
    
    /**
     * @ClassName: Application
     * @Description:
     * @Author: keke
     * @Date: 2021/4/7
     */
    public class Application {
    
        public static void main(String[] args) {
            Person person = new Person("keke");
            System.out.println(person.name);
        }
    
    }
    

Java simple memory diagram

code:

package com.keke.oop.demo03;

/**
 * @ClassName: Pet
 * @Description:
 * @Author: keke
 * @Date: 2021/4/7
 */
public class Pet {

    public String name;
    public int age;

    public void shout() {
        System.out.println("Let out a cry");
    }

}
package com.keke.oop.demo03;

/**
 * @ClassName: Application
 * @Description:
 * @Author: keke
 * @Date: 2021/4/7
 */
public class Application {
    public static void main(String[] args) {

        Pet dog = new Pet();
        dog.name = "Wangcai";
        dog.age = 3;

        dog.shout();

        System.out.println(dog.name);
        System.out.println(dog.age);

        Pet cat = new Pet();


    }
}

Memory map:

Simple summary of classes and objects

1. Class and object

A class is a template: abstract, and an object is an instance: concrete

2. Method

Define and call

3. Corresponding reference

Basic types (8 kinds) reference types: in addition to 8 basic types

Objects are operated by reference: stack - > heap (address)

4. Attribute: Field / member variable

Default initialization:

Number: 0.0

​ char: u0000

​ boolean: false

Reference: null

Definition: modifier attribute type attribute name = attribute value

5. Creation and use of objects

  • You must use the new keyword to create an object (call constructor) Person keke = new Person()
  • Object's attribute Keke name
  • Object's method Keke sleep()

6. Category

Static attributes are attributes

Dynamic behavior is method

encapsulation

  • The dew that should be exposed, the hide that should be hidden

Our program design should pursue "high cohesion and low coupling". High cohesion means that the internal data operation details of the class are completed by ourselves, and external interference is not allowed. Low coupling: only a small number of methods are exposed

For external use

  • Encapsulation (data hiding)

    Generally, direct access to the actual representation of data in an object should be prohibited, but should be accessed through the operation interface, which is called information hiding

  • Just remember this sentence: property private, get/set

package com.keke.oop.demo04;

/**
 * @ClassName: Student
 * @Description:
 * @Author: keke
 * @Date: 2021/4/8
 */
public class Student {

    //Property private
    //name
    private String name;
    //Student number
    private int id;
    //Gender
    private char sex;
    //Age
    private int age;

    //Provide some methods that can manipulate this property
    //That is, some public get and set methods are provided

    //Get: get this data
    public String getName() {
        return this.name;
    }

    //Set: set a value for this data
    public void setName(String name) {
        this.name = name;
    }

    //alt + insert: automatically generate set and get


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 120 || age < 0) {
            this.age = 3; //The illegal age is equal to three years old
        } else {
            this.age = age;
        }
    }
}
package com.keke.oop.demo04;

/**
 * @ClassName: Application
 * @Description:
 * @Author: keke
 * @Date: 2021/4/8
 */
public class Application {

    public static void main(String[] args) {

        /*
        * Summary: the significance of packaging
        * 1.Improve program security and protect data
        * 2.Implementation details of hidden code
        * 3.Unified interface
        * 4.System maintainability has increased
        * */

        Student s1 = new Student();

        s1.setName("keke");
        System.out.println(s1.getName());

        s1.setAge(999); //Illegal. You can set rules in the set method
        System.out.println(s1.getAge());

    }

}

inherit

  • The essence of inheritance is to abstract a group of classes, so as to realize better modeling of the real world

  • Extensions means "extension". A subclass is an extension of a parent class

  • Classes in Java only have single inheritance, not multiple inheritance, that is, a son can only have one father, but a father can have multiple sons

  • Inheritance is a relationship between classes. In addition, the relationship between classes includes dependency, composition, aggregation and so on

  • Two classes of inheritance relationship, one is a subclass (derived class) and the other is a subclass of the parent class (base class), which inherits the parent class and is represented by the keyword extends

  • In a sense, there should be a "is a" relationship between subclasses and superclasses

  • In Java, all classes inherit Object directly or indirectly by default

  • The class modified by the final keyword cannot be inherited and has no descendants

  • object class

  • super keyword

  • Method rewrite

Parent class: Person

package com.keke.oop.demo05;

/**
 * @ClassName: Person
 * @Description:
 * @Author: keke
 * @Date: 2021/4/8
 */
// Person: parent class
// In Java, all classes inherit Object directly or indirectly by default
public class Person {

    /*
    * public Then all subclasses and other classes can be used
    * If you change to private, its subclasses and other classes cannot be used
    * If it is replaced with protected, it can be used by subclasses under different packages from the parent class and other classes under the same package
    * If it is changed to default (i.e. neither write nor write), it can be used by subclasses and other classes under the same package as the parent class
    * */
    protected int money = 10_0000_0000;

    public void say() {
        System.out.println("Said a word");
    }

}

Subclass: Student, Teacher

package com.keke.oop.demo05;

/**
 * @ClassName: Student
 * @Description:
 * @Author: keke
 * @Date: 2021/4/8
 */
// Student is: subclass / derived class
// If a subclass inherits from the parent class, it will have all the methods of the parent class
public class Student extends Person {
    // ctrl + h: view the inheritance relationship of this class
}
package com.keke.oop.demo05;

/**
 * @ClassName: Student
 * @Description:
 * @Author: keke
 * @Date: 2021/4/8
 */
//Teacher is: subclass / derived class
public class Teacher extends Person {
}

Test class: Application

package com.keke.oop.demo05;

/**
 * @ClassName: Application
 * @Description:
 * @Author: keke
 * @Date: 2021/4/8
 */
public class Application {
    public static void main(String[] args) {
        Student student = new Student();
        student.say();
        System.out.println(student.money);

        Person person = new Person();
        int a = person.money;
    }
}

super keyword

First, you need to understand the effects of different access modifiers modifying attributes and methods:

public: all subclasses and other classes can be used
private: its subclasses and other classes cannot be used
protected: it can be used by subclasses under different packages from the parent class, subclasses under the same package and other classes
Default: it can be used by subclasses and other classes in the same package as the parent class

With visible: https://blog.csdn.net/qq_46601365/article/details/115561447

1. A class creation contains a parameterless constructor by default. If a parameterless constructor is displayed, the parameterless constructor will be overwritten

2. Calling a constructor using the super keyword can only be called by the constructor of this class, not by the member methods and static methods of this class

3. super can only appear in subclass methods or constructor methods

4. Both the parameterless construction method and the parameterless construction method of the subclass will be prompted to call the construction method of the parent class during the creation process of Alt+ins, and the construction method of the parent class must be called. If the parameterless construction of the parent class is selected, it will not be displayed. It is in the first line by default, and the display must also be in the first line; If the parameterized structure of the parent class is selected, it will be displayed in the first row by default. Yes and only one. If there is a son, there must be a father

5. The subclass constructor cannot call the parent class and its own constructor at the same time, that is, super and this cannot call the constructor at the same time, that is, the subclass constructor cannot call its own constructor and constructor

VS this

Different representative objects: this: the caller of itself, this object super: the application of the parent object

Premise: this: it can be used without inheritance. super: it can only be used under inheritance conditions

Constructor: this(): call constructor of this class super: call constructor of parent class

Parent class:

package com.keke.oop.demo06;

/**
 * @ClassName: Person
 * @Description:
 * @Author: keke
 * @Date: 2021/4/8
 */
// Person: parent class
public class Person {

    protected String name = "keke";

    //Note: private things cannot be inherited
    public void print() {
        System.out.println("Person");
    }

    public Person() {

    }

    public Person(String name) {
        //this();
        this.name = name;
        System.out.println("Person No participation");
    }
}

Subclass:

package com.keke.oop.demo06;

/**
 * @ClassName: Student
 * @Description:
 * @Author: keke
 * @Date: 2021/4/8
 */
// Student is: subclass / derived class
// If a subclass inherits from the parent class, it will have all the methods of the parent class
public class Student extends Person {

    private String name = "qingjiang";


    public void test(String name) {
        System.out.println(name); //Ke Ke
        System.out.println(this.name); //qingjiang
        System.out.println(super.name); //keke
    }

    /*public void print() {
        System.out.println("Student");
    }*/

    public void test1() {
        print(); //Student
        this.print(); //Student
        super.print(); //Person
//        super(); //Call to 'super()' must be first statement in constructor body: constructor can only be called by constructor of this class and must be in the first line
    }

    public Student() {

        //Hidden code: the parameterless construction of the parent class is called
        //Note: if super() is displayed, the parameterless construction of the calling parent class must be written in the front, otherwise an error will be reported
//        super();
        //A subclass parameterless constructor cannot call its parent class and its own constructor at the same time, that is, super and this cannot call the constructor at the same time, that is, a subclass parameterless constructor cannot call its own parameterless constructor and parameterless constructor
//        this();

        //When the parent class does not contain a parameterless construct, the child class construct must display the parameterless construct that calls the parent class
//        super("aaa");

        System.out.println("Student No participation");

    }

    public Student(String name, String name1) {
        super(name);
        this.name = name1;
    }

    public Student(String name) {
        //The parent class is called with no parameters
        //Note: if super() is displayed, the parameterless construction of the calling parent class must be written in the front, otherwise an error will be reported
//        super();
        //A subclass parameterless constructor cannot call its parent class and its own constructor at the same time, that is, super and this cannot call the constructor at the same time, that is, a subclass parameterless constructor cannot call its own parameterless constructor and parameterless constructor
//        this();

        //When the parent class does not contain a parameterless construct, the child class construct must display the parameterless construct that calls the parent class
        super("aaa");

        this.name = name;

        System.out.println("Student There are participants in the implementation");
    }

}

package com.keke.oop.demo06;


/**
 * @ClassName: Student
 * @Description:
 * @Author: keke
 * @Date: 2021/4/8
 */

//Teacher is: subclass / derived class
public class Teacher extends Person {
}

Test class:

package com.keke.oop.demo06;

/**
 * @ClassName: Application
 * @Description:
 * @Author: keke
 * @Date: 2021/4/8
 */
public class Application {
    public static void main(String[] args) {
        Person person = new Person("aaa");
        person.print();
//        student.test("Keke");

//        student.test1();
    }
}

Method rewrite

Rewrite premise:

1. Inheritance relationship is required. The subclass overrides the method of the parent class

2. Method names must be the same

3. The parameter list must be the same

4. Modifier: the scope can be expanded but not reduced: public > protected > Default > private

5. Exception thrown: the scope can be reduced but not expanded: for example: classnotfoundexception -- > exception (large)

Note:

1. Rewriting is the rewriting of methods and has nothing to do with properties

2. Rewriting is only for non static methods. Methods decorated with static, final and private cannot be rewritten

3. The method of the subclass and the parent class must be consistent, and the method body is different!

Why rewrite:

The function of the parent class and the subclass are not necessarily required or satisfied

Parent class:

package com.keke.oop.demo07;

/**
 * @ClassName: B
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
//Rewriting is the rewriting of methods and has nothing to do with properties
public class B {

    public void test() {
        System.out.println("B=>test()");
    }

    public static void testStatic() {
        System.out.println("B=>testStatic()");
    }

}

Subclass:

package com.keke.oop.demo07;

/**
 * @ClassName: A
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class A extends B {

    //alt + ins: select override: override the method of the parent class
    @Override //Comments: functional comments! Override: override
    public void test() {
//        super.test(); // The method of the parent class is called by default
        System.out.println("A=>test"); //Rewrite your own code
    }


    public static void testStatic() {
        System.out.println("A=>testStatic()");
    }

}

Test class:

package com.keke.oop.demo07;

/**
 * @ClassName: Application
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Application {

    public static void main(String[] args) {

        A.testStatic(); //A=>testStatic()
        B.testStatic(); //B=>testStatic()

        A a = new A();
        a.test(); //A=>test()

        //The reference of the parent class points to the child class object
        B b = new A();
        b.test(); //A=>test()

        /*
        * Conclusion: rewriting is only for non static methods
        * */

    }

}

polymorphic

  • That is, the same method can adopt many different behavior modes according to different sending objects

  • The actual type of an object is determined, but there are many types of references that can point to the object

  • Conditions for the existence of polymorphism

There is an inheritance relationship

Subclass overrides the method of the parent class

A parent class reference points to a child class object

  • Note: polymorphism is the polymorphism of methods, and there is no polymorphism of attributes

  • instanceof

  • Summary:

  • The methods that can be executed by an object mainly depend on the type on the left of the object, which has little to do with the right

Example: after the reference of the parent class points to the object of the subclass, an error will be reported if a method specific to the subclass is called, but it can be forcibly converted to a subclass object and then called

  • After the reference of the parent class points to the object of the child class, the object calls the overridden method and executes the overridden method of the child class

  • Supplement:

  • Compile time polymorphism: method overload

  • Runtime polymorphism: Method override

  • Runtime polymorphism is the quintessence of object-oriented. Two things need to be done to realize polymorphism: 1 Method override (the subclass inherits the parent class and overrides the existing or abstract methods in the parent class); 2. Object modeling (use the parent type reference to refer to the sub type object, so that the same reference calls the same method, which will show different behavior according to the different sub class objects).

Parent class:

package com.keke.oop.demo08;

/**
 * @ClassName: Person
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Person {

    public void run() {
        System.out.println("run");
    }

}

Subclass:

package com.keke.oop.demo08;

/**
 * @ClassName: Student
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Student extends Person {

    @Override
    public void run() {
        System.out.println("son");
    }

    public void eat() {
        System.out.println("eat");
    }

}

Test class:

package com.keke.oop.demo08;

/**
 * @ClassName: Application
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Application {

    public static void main(String[] args) {

        //The actual type of an object is determined
//        new Student();
//        new Person();

        //However, the type of reference that can be pointed to is uncertain
        //The methods that students can call are their own or inherit the parent class
        Student s1 = new Student();
        //The Person parent type can point to subclasses, but cannot call methods unique to subclasses
        Person s2 = new Student(); //The reference of the parent class points to the object of the child class
        Object s3 = new Student();

        s2.run(); //The subclass overrides the method of the parent class and executes the method of the subclass
        s1.run();

        //The methods that can be executed by an object mainly depend on the type on the left of the object, which has little to do with the right
//        s2.eat(); // report errors
        ((Student) s2).eat(); //Can be called after cast
        s1.eat();

    }

}

instanceof

instanceof is used to judge the type of an object and the reference type

**X instanceof Y: **

Whether the compilation can pass: it depends on whether there is a parent-child relationship between X and Y. if there is, the compilation will pass, and if there is no, the compilation will fail

true or not: depends on whether the object type pointed to by X is a subtype of Y or the Y type itself

Parent class:

package com.keke.oop.demo09;

/**
 * @ClassName: Person
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Person {

    public void run() {
        System.out.println("run");
    }

}

Subclass:

package com.keke.oop.demo09;

/**
 * @ClassName: Student
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Student extends Person {
}
package com.keke.oop.demo09;

/**
 * @ClassName: Teacher
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Teacher extends Person {
}

Test class:

package com.keke.oop.demo09;

/**
 * @ClassName: Teacher
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Application {

    public static void main(String[] args) {

        //Object > String
        //Object > Person > Teacher
        //Object > Person > Student
        Object object = new Student();

        System.out.println(object instanceof Student); //true
        System.out.println(object instanceof Person); //true
        System.out.println(object instanceof Object); //true
        System.out.println(object instanceof Teacher); //false
        System.out.println(object instanceof String); //false

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

        Person person = new Student();

        System.out.println(person instanceof Student); //true
        System.out.println(person instanceof Person); //true
        System.out.println(person instanceof Object); //true
        System.out.println(person instanceof Teacher); //false
//        System.out.println(person instanceof String); // Compilation error

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

        Student student = new Student();

        System.out.println(student instanceof Student); //true
        System.out.println(student instanceof Person); //true
        System.out.println(student instanceof Object); //true
//        System.out.println(student instanceof Teacher); // Compilation error
//        System.out.println(student instanceof String); // Compilation error

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

        Person person1 = new Person();

        System.out.println(person1 instanceof Student); //false
        System.out.println(person1 instanceof Person); //true
        System.out.println(person1 instanceof Object); //true
        System.out.println(person1 instanceof Teacher); //false
//        System.out.println(person1 instanceof String); //false
    }

    /*
    * System.out.println(X instanceof Y);
    * Whether the compilation can pass: it depends on whether there is a parent-child relationship between X and Y. if there is, the compilation will pass, and if there is no, the compilation will fail
    * true or not: depends on whether the object type pointed to by X is a subtype of Y or the Y type itself
    * */

}

Reference type conversion

1. Conversion between reference types: conversion between parent and child classes

2. Prerequisite: the parent class reference points to the child class object

  • Downward transformation (coercion): parent - > child

  • Upward Transformation: child - > parent, some subclass specific methods will be lost

3. Function: convenient method call and reduce repeated code

Parent class:

package com.keke.oop.demo10;

/**
 * @ClassName: Person
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Person {

    public void run() {
        System.out.println("run");
    }

}

Subclass:

package com.keke.oop.demo10;

/**
 * @ClassName: Student
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Student extends Person {

    public void go() {
        System.out.println("go");
    }

}

Test class:

package com.keke.oop.demo10;

/**
 * @ClassName: Teacher
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Application {

    public static void main(String[] args) {

        //Conversion between reference types: parent and child

        //High - > low
        Person obj = new Student();
//        obj.go(); // Parent class reference points to subclass object: subclass specific methods cannot be called

        //If you convert the obj object to the Student type, you can use the methods specific to the Student class
        //Downward transformation
        ((Student) obj).go();

        //When a subclass is converted to a parent class, some of its original methods may be lost
        Student student = new Student();
        student.go();
        Person person = student; // Low - > high up conversion
//        person.go(); // report errors

    }
}

static keyword

  • effect:

1. Modify the member variable - > class variable in the class: it can be accessed through the class name without new object

2. Modify the member method in the class (non static method) - > static method: it can be accessed through the class name, and no new object is required

package com.keke.oop.demo11;

/**
 * @ClassName: Student
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Student {

    private static int age; //Static variable
    private double score; //Member variable / non static variable

    public void run() {
//        go(); // Static methods can be called directly in member methods
    } //Member method / non static method

    public static void go() {
//        run(); // Member methods cannot be called directly in static methods with error reports
//        Student student = new Student();
//        student.run();
    } //Static method

    public static void main(String[] args) {
        Student s1 = new Student();

//        System.out.println(s1.age);
        System.out.println(Student.age); //Class name calling is recommended
        System.out.println(s1.score);
//        System.out.println(Student.score); // report errors


        new Student().run();
        Student.go();
        go(); //Because in this class, the class name can be omitted.

    }

}

3. Static code block: the class is executed upon loading and only once

package com.keke.oop.demo11;

/**
 * @ClassName: Person
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Person {

    //2
    {
        //When this program is not called, it is not recommended to automatically create the object without the name of the active constructor (before the active constructor is called):
        //Function: assign initial value
        System.out.println("Anonymous code block");
    }

    //1
    static {
        //Static code block (recommended): the class is executed upon loading and only once
        System.out.println("Static code block");
    }

    //3
    public Person() {
        System.out.println("Construction method");
    }

    public static void main(String[] args) {
        Person person = new Person(); //Static code block anonymous code block construction method
        System.out.println("=================");
        Person person1 = new Person(); //Static code block anonymous code block construction method
    }

}

4. Static import package: import class methods directly into the current class, so that class methods can be called directly using "method name", which is more convenient

package com.keke.oop.demo11;

//Static import package
import static java.lang.Math.random;
import static java.lang.Math.PI;

/**
 * @ClassName: Test
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Test {

    public static void main(String[] args) {
//        System.out.println(Math.random());
        System.out.println(random()); //After using the static import package, you can directly write the random() method without writing Math
        System.out.println(PI);
    }

}
  • be careful:

    1. Static methods can be called directly in member methods, but member methods cannot be called directly in static methods. You need to new an object through object call. Because the attributes and methods modified with the static keyword are loaded with the class in memory, they can be called directly through the class name

abstract class

  • The abstract modifier can be used to modify a method or a class. If you modify a method, the method is an abstract method; If you modify a class, it is an abstract class

  • Abstract classes can have no abstract methods, but classes with abstract methods must be declared as abstract classes

  • Abstract class. You cannot use the new keyword to create objects. It is used to let subclasses inherit

  • Abstract methods have only method declarations and no method implementations. They are used to implement subclasses

  • If a subclass inherits an abstract class, it must implement the abstract method that the abstract class does not implement, otherwise the subclass must also be declared as an abstract class

  • Significance of existence: define the public methods of some classes together, and then create these classes to inherit the abstract classes, so as to avoid the repeated writing of these class public methods, simplify the development of code and improve the development efficiency and expansibility

  • The most important thing to be an architect is whether you have abstract thinking!

Abstract class:

package com.keke.oop.demo12;

/**
 * @ClassName: Action
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
//Abstract modified classes represent abstract classes. Classes can only inherit from one class, and interfaces can inherit from multiple classes
public abstract class Action {

    //Abstract, abstract method, only method name, no method implementation
    public abstract void doSomething();

    //characteristic:
    //1. The new keyword cannot be used to create objects. It is used to make subclasses inherit, which is equivalent to a constraint
    //2. Ordinary methods can be written in abstract classes
    //3. Abstract methods must be in abstract classes

    public void hello() {
        System.out.println("Common method");
    }

}

Subclass:

package com.keke.oop.demo12;

/**
 * @ClassName: A
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
//If a subclass inherits an abstract class, it must implement the abstract method that the abstract class does not implement, otherwise the subclass must also be declared as an abstract class
public class A extends Action {
    @Override
    public void doSomething() {

    }
}

Test class:

package com.keke.oop.demo12;

/**
 * @ClassName: Application
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public class Application {

    public static void main(String[] args) {
        //    new Action(); // report errors
        Action a = new A();
    }

}

Thinking: an abstract class cannot be new, so does it have a constructor?

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

public abstract class Action {
    public Action() {
    }

    public abstract void doSomething();

    public void hello() {
        System.out.println("aaa");
    }
}

Answer: through javac action Action generated by Java command Class file shows that there is a constructor for the abstract class

Interface

  • Common class: only concrete implementation

  • Abstract classes: both concrete implementations and specifications (abstract methods) exist

  • Interface: there are only specifications, but you can't write method professional constraints. The separation of implementation constraints and Implementation: that is, interface oriented programming

  • An interface is a specification. It defines a set of rules, which embodies the idea of "if you are... You must be able to..." in the real world. If you are an angel, you must be able to fly. If you are a car, you must be able to run. If you are a good man, you must be a bad man; If you are a bad person, you must bully the good person.

  • The essence of an interface is a contract. Just like the laws among us, we all abide by it after it is formulated

  • The essence of OOP is the abstraction of objects, which is best reflected in the interface. Why we discuss design patterns only for languages with abstract ability (such as java, C + +, c# etc.) is because what design patterns study is actually how to abstract reasonably

Function of interface:

1. Interface is essentially a constraint and specification

2. Some methods are defined for different people to implement. For example, ten classes implement an interface, but the implementation methods are different

3. In fact, all defined methods in the interface are abstract. public abstract is provided by default

4. All defined attributes in the interface are static constants. public static final is provided by default and cannot be changed, but generally, attributes are not defined in the interface

5. The interface cannot be instantiated because there is no constructor in the interface

6. A class can implement multiple interfaces using the implements keyword

7. Implementing an interface must override all abstract methods in the interface

New features of Java 8:

1. Static methods can be defined in the interface (static modification must be used). They are not abstract and concrete. They can be called directly using the interface name

2. The default method can be defined in the interface (it must be decorated with default). The default method is a non static method. Non static methods can only be called through objects, but the interface cannot create the name of objects. Therefore, we need subclasses to implement the interface

In addition, it is worth noting that in object-oriented, java only supports single inheritance and does not support multiple inheritance. A class can only inherit one class,

(1) If multiple interfaces define the same static method,

Even if there is an implementation class that implements multiple interfaces at the same time, it is still a method that cannot call the interface with the implementation class name

(2) If multiple interfaces define the same default method

When the implementation class implements multiple interfaces, the default method must be rewritten, otherwise the compilation fails.

The difference between interface and abstract class

Note: abstract method: it must be modified by abstract, not private, static, synchronized and native. It must end with a semicolon without curly brackets.

1. The keyword to implement the interface is implements, and the keyword to inherit the abstract class is extends. A class can implement multiple interfaces, but a class can only inherit one abstract class. Therefore, multiple inheritance can be realized indirectly by using interfaces.

2. Abstract methods (modified by public abstract by default and cannot be modified), default methods (modified by default) and static methods (modified by public by default and cannot be changed) can be defined in the interface. Attributes can be defined, but they are static constants. public static final is built by default and cannot be changed. Initial values must be assigned and classes cannot be modified;

Abstract methods, static methods, member methods, static attributes and non static attributes can be defined in abstract classes. Abstract methods must be displayed and modified by abstract.

3. Advantages of abstract classes: if you add a new concrete method to an abstract class, all its subclasses will get the new method at once, which the Java interface can't do. If you add a new method to a Java interface, all classes that implement the interface will fail to compile successfully, Because you have to make every class implement this method again, which is obviously the disadvantage of Java interface

Advantages of interface: the implementation of an abstract class can only be given by the subclass of the abstract class, that is, the implementation is in the hierarchical structure of inheritance defined by the abstract class. Due to the single inheritance of Java language, the effectiveness of the abstract class as a type definition tool is greatly reduced. At this point, the advantages of java interface come out. Any class that implements the methods specified by a java interface can have the type of this interface, and a class can implement any number of Java interfaces, so this class has many types. (if you use an abstract class, the subclass type that inherits from this abstract class is relatively single, because the subclass can only inherit the abstract class; while the subclass can implement multiple interfaces at the same time, because there are many types. Both interfaces and abstract classes can define objects, but they can only be instantiated with their specific implementation classes.) From this point, it is not difficult to see that Java interface is an ideal tool for defining mixed types. Mixed classes indicate that a class not only has the behavior of a primary type, but also has other secondary behaviors.

4. Combining the respective advantages of the abstract class and java interface in the three points, a classic design pattern comes out: the work of declaring the type is still undertaken by the java interface, but at the same time, a Java abstract class is given and the interface is implemented, while other concrete classes belonging to the abstract type can choose to implement the java interface or inherit the abstract class, In other words, in the hierarchy, the java interface is at the top, followed by the abstract class. The greatest advantages of the next two can be brought into full play. This mode is the "default adaptation mode". This pattern is used in the Java language API, and all follow a certain naming standard: Abstract + interface name. (A extends AbstractB implements interfaceC, then a can choose to implement the methods in (@ Override) interface interfaceC or not; A can choose to implement (@ Override) the methods in the abstract class AbstractB or not)

Benefits of default adaptation mode: suppose an interface is designed, but the subclasses that implement this interface do not need to implement all the methods in the interface, that is, there are too many methods in the interface, which are redundant for some subclasses, so we have to waste writing an empty implementation; At this time, you can define an abstract class to implement the interface, and empty implement all the abstract methods in the interface, so that the subsequent specific subclasses only need to inherit the abstract class and rewrite the methods they want to implement. In addition, you can also define extraction methods in the abstract class, and you can also implement an interface to maximize the advantages of the abstract class and interface!

Interface:

package com.keke.oop.demo13;

/**
 * @ClassName: TimeService
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
public interface TimeService {
    void timer();
}
package com.keke.oop.demo13;

/**
 * @ClassName: UserService
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
//The keywords defined by interface and interfaces need to have implementation classes
public interface UserService {

    //All defined attributes in the interface are static constants. public static final is provided by default, but generally, attributes are not defined in the interface
    int AGE = 99;

    //In fact, all defined methods in the interface are abstract. public abstract is provided by default
    void add(String name);
    void delete(String name);
    void update(String name);
    void query(String name);

    static void aaa() {};
}

Abstract class:

package com.keke.oop.demo13;

/**
 * @ClassName: UserService
 * @Description:
 * @Author: keke
 * @Date: 2021/4/10
 */
//Class can implement the implements interface
//A class that implements an interface must override all abstract methods in the interface
//Multiple inheritance can be realized by using interfaces
public abstract class UserServiceAbstract implements UserService, TimeService{
    @Override
    public void timer() {

    }

    @Override
    public void add(String name) {

    }

    @Override
    public void delete(String name) {

    }

    @Override
    public void update(String name) {

    }

    @Override
    public void query(String name) {

    }
}

Implementation class:

package com.keke.oop.demo13;

/**
 * @ClassName: UserServiceImpl
 * @Description:
 * @Author: keke
 * @Date: 2021/4/11
 */
public class UserServiceImpl extends UserServiceAbstract {

    @Override
    public void add(String name) {
        System.out.println("add");
    }

    @Override
    public void delete(String name) {
        System.out.println("delete");
    }

}

Inner class

  • Internal class is to define another class inside a class. For example, if class B is defined in class A, class B is called internal class relative to class A, and class A is called external class relative to class B

1. Member internal class

2. Static internal class

3. Local internal class

4. Anonymous inner class

package com.keke.oop.demo14;

/**
 * @ClassName: Outer
 * @Description:
 * @Author: keke
 * @Date: 2021/4/11
 */
public class Outer {

    private int id = 10;
    private static int id2 = 20;

    private void out() {
        System.out.println("This is the method of an external class");
    }

    private static void out2() {
        System.out.println("This is method 2 of the external class");
    }

    public void test() {
        System.out.println("Method for testing anonymous inner classes");
    }

    //Member inner class
    public class Inner {
        public void in() {
            System.out.println("This is the method of the inner class of the member");
        }

        //Get the private properties and methods of the external class~
        public void getID() {
            System.out.println(id);
            out();
            System.out.println(id2);
            out2();
        }
    }

    //Static inner class
    public static class Inner2 {
        public void in() {
            System.out.println("This is the method of the static inner class");
        }

        //You can only obtain static private properties and static private methods ~, because static properties, methods and classes will be instantiated first
        public void getID() {
//            System.out.println(id);
//            out();
            System.out.println(id2);
            out2();
        }
    }

    //Local inner class: written in the method of the outer class
    public testInner3 method() {
        class Inner3 implements testInner3 {  //There cannot be an access modifier here
            public void in() {
                System.out.println("This is the method of the local inner class");
            }
        }

        return new Inner3();
    }

}

//A Java class can have pairs of class classes, but only one public class
/*public*/ class A {
    public static void main(String[] args) {

    }
}

interface testInner3 {
    void in();
}

Test class:

package com.keke.oop.demo14;

/**
 * @ClassName: Applicaiton
 * @Description:
 * @Author: keke
 * @Date: 2021/4/11
 */
public class Application {

    public static void main(String[] args) {
        Outer outer = new Outer();
        //Instantiate the inner class through this outer class~
        Outer.Inner inner = outer.new Inner();
        inner.in();
        inner.getID();

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

        //Calling methods of local inner classes
        testInner3 inner3 = outer.method();
        inner3.in(); //This is the method of the local inner class

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

        //Anonymous inner class: there is no name to initialize the class, so there is no need to save the instance to the variable
        new Outer().test();

        //Commonly used to implement interfaces
        new UserService() {
            @Override
            public void hello() {

            }
        };
    }

}

interface UserService {
    void hello();
}

Topics: Java