Java object oriented

Posted by qhiiyr on Sun, 26 Dec 2021 20:31:21 +0100

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 simple things

object-oriented:

  • Birds of a feather flock together and classify. Thinking about the problem will first solve what classifications the problem needs, and then think about these classifications separately. Finally, process oriented thinking is carried out on the details under a certain classification.
  • Object oriented is suitable for dealing with complex problems and problems requiring multi person cooperation.

Overview: for describing complex things, in order to grasp them macroscopically and analyze them reasonably as a whole, we need to use object-oriented thinking to analyze the whole system. However, specific to micro operation, it still needs process oriented thinking to deal with it.

What is object oriented?

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

Three characteristics:

  • encapsulation
  • inherit
  • polymorphic

be careful:

  • From the perspective of epistemology, there are objects before classes. Because objects are concrete and classes are abstract. A class is an abstraction of an object.
  • From the perspective of code operation, there are classes before objects. A class is a template for an object.

Relationship between class and object

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

  • Such as: people, animals, plants, computers, mobile phones, etc

Objects are concrete instances of abstract concepts.

  • For example, Zhang San, Mimi, the little cat next door, and the dog named Wangcai in Tang Bohu ordering autumn fragrance

Initializing and creating objects

Creation method: use the new keyword to create an object

When using the new keyword to create an object, in addition to allocating memory space, it will also assign a default value to the created object for initialization and call the constructor in the class.

Example:

Student class

package com.wmwx.oop.Demo01;

//Student class
public class Student {
    //Properties: Fields
    String name;
    int age;

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

Application class (startup class)

package com.wmwx.oop.Demo01;

//Startup class
public class Application {
    //There should be only one main method in a project
    public static void main(String[] args) {
        //Class is abstract and needs to be instantiated
        //Class will return its own object after instantiation
        //The student object is an instance of the student class
        Student student = new Student();
        student.study();        //Output "student is learning."
        student.name = "Xiao Ming";
        student.study();        //Output "student Xiao Ming is studying."
    }
}

Construction method

When an object is created, the constructor is used to initialize the object. The constructor has the same name as its class, but the constructor has no return value.

Even if a class doesn't write anything, there will be a constructor. Because Java automatically provides a default constructor, its access modifier is the same as that of the class.

Once you define a constructor, the default constructor will fail.

Example:

Person class:

package com.wmwx.oop.Demo01;

public class Person {
    String name;
    //The shortcut alt+insert can be used to automatically generate construction methods
    //Nonparametric structure
    public Person(){
        this.name = "An anonymous";
    }

    //Parameterized construction (once a parameterized construction is defined, a nonparametric construction must be explicitly defined)
    public Person(String name){
        this.name = name;
    }
}

Application class:

package com.wmwx.oop.Demo01;

public class Application {
    public static void main(String[] args) {
        //Using the new keyword is essentially calling the constructor
        Person person1 = new Person();                      //Call parameterless construction
        System.out.println(person1.name);                   //Output "an anonymous"
        //Using the construction method, you can initialize the object
        Person person2 = new Person("Vivid sky");       		 //Call parameterized construction
        System.out.println(person2.name);                   //Output "vivid sky"
    }
}

Memory analysis

The process is as follows:

  1. Create class
  2. Store classes and static methods in classes in the heap
  3. create object
  4. Make room for objects in the heap
  5. Store the reference variable name of the object in the stack
  6. Make the reference variable name of the object point to the space opened in the heap

encapsulation

The so-called encapsulation means the dew that should be exposed and the Tibet that should be hidden. Programming should pursue * * "high cohesion, low coupling" * *.

High cohesion: the internal data operation details of the class are completed by themselves, and external interference is not allowed.

Low coupling: only a small number of methods are exposed for external use.

For the code, it can be summed up in one sentence: property private, get/set.

significance:

  • Improve program security and protect data
  • Implementation details of hidden code
  • Unified interface
  • The maintainability of the system is improved

Example:

Student class:

package com.wmwx.oop.Demo03;

public class Student {
    //Property private
    private String name;
    private int id;
    private String gender;
    private int age;

    //Common get and set methods need to be provided
    //Get method: get data
    public String getName() {
        return name;
    }
    //Set method: set data
    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age<0||age>120){
            this.age = 3;
        }else{
            this.age = age;
        }
    }
}

Application class:

package com.wmwx.oop;

import com.wmwx.oop.Demo03.Student;

//Startup class
public class Application {
    public static void main(String[] args) {
        Student student = new Student();
        student.setName("Vivid sky");
        student.setId(123456);
        student.setGender("male");
        student.setAge(130);
        System.out.println(student.getAge());   //Output 3
    }
}

inherit

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

In Java, you can declare that a class inherits from another class through the extends keyword. Its syntax is as follows:

class Subclass extends Parent class {
}

Extensions means extension, and subclasses are extensions to parent classes.

Notes on inheritance:

  • Java has only single inheritance, not multiple inheritance.
  • In Java, all classes inherit directly or indirectly from the Object class by default.

In Java, you can use this to refer to the current class and super to refer to the parent class.

Precautions for super:

  • super calls the constructor of the parent class, which must be in the first line of the constructor.
  • super can only appear in methods or constructors of subclasses.
  • super and this cannot call constructor at the same time.

Rewriting is a subclass's rewriting of the implementation process of the accessible methods of the parent class, and the return value and formal parameters cannot be changed. The advantage of rewriting is that subclasses can define their own specific behavior as needed. In other words, the subclass can implement the methods of the parent class as needed. Rewriting requires the following rules:

  • Method names must be the same
  • The parameter list must be the same
  • The range of modifiers can be expanded, but not reduced
  • Exceptions thrown can be shrunk, but not enlarged

Example:

Person class:

package com.wmwx.oop.Demo04;

//Parent: Human
public class Person {
    private int money = 10_0000_0000;
    protected String name = "Vivid sky";

    public Person() {
        System.out.println("Person The parameterless construction method of is executed!");
    }

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

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

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

Student class:

package com.wmwx.oop.Demo04;

//Sub category: Student
public class Student extends Person{
    private String name = "Miao Xiao";

    public Student() {
        //Hidden code: super();
        //The constructor of the parent class must be in the first line of the constructor of the child class
        System.out.println("Student The parameterless construction method of is executed!");
    }

    public void test1(String name){
        System.out.println(name);           //Output parameters
        System.out.println(this.name);      //Output the name of the current class
        System.out.println(super.name);     //Output the name of the parent class
    }

    //Rewriting is the rewriting of methods and has nothing to do with properties
    //Only public methods are allowed to be overridden
    //You can use the shortcut alt+insert to insert the override method
    @Override
    public void print() {
        System.out.println("Student");
    }

    public void test2(){
        print();
        this.print();
        super.print();
    }
}

Application class:

package com.wmwx.oop;

import com.wmwx.oop.Demo04.Person;
import com.wmwx.oop.Demo04.Student;

//Startup class
public class Application {
    public static void main(String[] args) {
        Student student = new Student();
        //The first line outputs "the parameterless construction method of Person has been executed!"
        //The second line outputs "Student's parameterless construction method has been executed!"
        student.say();      //If a subclass inherits from the parent class, it will have the public method of the parent class
        System.out.println(student.getMoney()); //You can use the get/set method of the parent class to operate on the property
        //You can use the shortcut ctrl+H to view the inheritance tree
        student.test1("MiaoXiao");
        //The first line outputs "MiaoXiao"
        //The second line outputs "Miaoxiao"
        //The third line outputs "wonderful and beautiful"
        student.test2();
        //The first line outputs "Student"
        //The second line outputs "Student"
        //The third line outputs "Person"
        Student stu1 = new Student();
        stu1.print();   //Output "Student"
        //A reference to a parent class points to a child class
        Person stu2 = new Student();
        stu2.print();   //Output "Student"
    }
}

polymorphic

Polymorphism is the ability of the same behavior to have multiple different forms or forms. When calling a method in a polymorphic way, first check whether the method exists in the parent class. If not, the compilation error will occur; If so, call the method with the same name of the subclass.

There are three necessary conditions for polymorphism:

  • inherit
  • rewrite
  • The parent class reference points to the child class object: Parent p = new Child();

Methods that cannot be overridden:

  • static method
  • final method
  • private method

Example:

Person class:

package com.wmwx.oop.Demo05;

public class Person {
    public void run(){
        System.out.println("People are running.");
    }
}

Student class:

package com.wmwx.oop.Demo05;

public class Student extends Person{
    @Override
    public void run() {
        System.out.println("The students are running.");
    }

    public void eat(){
        System.out.println("The students are eating.");
    }
}

Application class:

package com.wmwx.oop;

import com.wmwx.oop.Demo05.Person;
import com.wmwx.oop.Demo05.Student;

//Startup class
public class Application {
    public static void main(String[] args) {
        //The actual type of an object is determined
        //However, the type of reference that can be pointed to is uncertain
        Student s1 = new Student();
        Person s2 = new Student();      //A reference to a parent class points to a child class
        Object s3 = new Student();
        s1.run();       //Output "student running"
        s2.run();       //The subclass overrides the parent class method, which will execute the subclass method and output "students running."
        s1.eat();       //Output "students are eating"
        //s2.eat();     // Cannot call. The methods that objects can use depend on the types on the left.
        ((Student)s2).eat();    //Cast type. Output "students are eating."
    }
}

instanceof

The instanceof keyword in Java can be used to judge whether an object is an instance of a class. If yes, return true; If not, false is returned; If the two are irrelevant, the compilation fails.

Example:

package com.wmwx.oop;

import com.wmwx.oop.Demo06.Person;
import com.wmwx.oop.Demo06.Student;
import com.wmwx.oop.Demo06.Teacher;

//Startup class
public class Application {
    public static void main(String[] args) {
        //The inheritance relationship is as follows:
        //Object -> Person -> Student
        //Object -> Person -> Teacher
        //Object -> String
        Object object = new Student();
        System.out.println(object instanceof Student);  //Output true
        System.out.println(object instanceof Person);   //Output true
        System.out.println(object instanceof Object);   //Output true
        System.out.println(object instanceof Teacher);  //Output false
        System.out.println(object instanceof String);   //Output false
        System.out.println("=====");
        Person person = new Student();
        System.out.println(person instanceof Student);  //Output true
        System.out.println(person instanceof Person);   //Output true
        System.out.println(person instanceof Object);   //Output true
        System.out.println(person instanceof Teacher);  //Output false
        //System.out.println(person instanceof String); // Compile error
        System.out.println("=====");
        Student student = new Student();
        System.out.println(student instanceof Student);  //Output true
        System.out.println(student instanceof Person);   //Output true
        System.out.println(student instanceof Object);   //Output true
        //System.out.println(student instanceof Teacher);// Compile error
        //System.out.println(student instanceof String); // Compile error
    }
}

Type conversion

  • When a child class is converted to a parent class, it is an upward transformation and can be automatically converted.
  • Converting a parent class to a child class is a downward transformation and requires forced conversion.

Example:

Person class:

package com.wmwx.oop.Demo06;

public class Person {
    public void run(){
        System.out.println("People are running.");
    }
}

Student class:

package com.wmwx.oop.Demo06;

public class Student extends Person{
    public void walk(){
        System.out.println("The students are walking.");
    }
}

Application class:

package com.wmwx.oop;

import com.wmwx.oop.Demo06.Person;
import com.wmwx.oop.Demo06.Student;

//Startup class
public class Application {
    public static void main(String[] args) {
        //High ------------- low
        Person person = new Student();
        ((Student)person).walk();   //Cast type

        Student student = new Student();
        Person obj = student;       //Some methods may be lost when a subclass is converted to a parent class
        //obj.walk();               // Compile error
    }
}

Static code block

Static code blocks are executed when the class is loaded and only once.

Example:

Person class:

package com.wmwx.oop.Demo07;

public class Person {
    //For the second execution, the initial value can be assigned here
    {
        System.out.println("Anonymous code block");
    }

    //First execution, only once
    static {
        System.out.println("Static code block");
    }

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

Application class:

package com.wmwx.oop;

import com.wmwx.oop.Demo07.Person;

//Startup class
public class Application {
    public static void main(String[] args) {
        Person person = new Person();
        //The first line outputs "static code block"
        //The second line outputs "anonymous code block"
        //The third line outputs "construction method"
    }
}

abstract class

Abstract is used to define abstract classes in the Java language. Its basic syntax is as follows:

abstract class Class name{
    //attribute
    //method
}

Except that an abstract class cannot instantiate an object, other functions of the class still exist. The access methods of member variables, member methods and constructor methods are the same as those of ordinary classes.

Because abstract classes cannot instantiate objects, they must be inherited before they can be used. In Java, a class can only inherit one abstract class, but a class can implement multiple interfaces.

Abstract is used in the Java language to define abstract methods. Its basic syntax is as follows:

abstract Access modifier return value type method name(parameter);

Rules for abstract classes and methods:

  • Abstract classes cannot be instantiated (that is, they cannot be new). Only non Abstract subclasses of abstract classes can create objects.
  • Abstract classes do not necessarily contain abstract methods, but classes with abstract methods must be abstract classes.
  • The abstract method in the abstract class is only a declaration and does not contain the method body, that is, the specific implementation of the method is not given.
  • Constructor and class methods (Methods decorated with static) cannot be declared as abstract methods.
  • A subclass of an abstract class must give a concrete implementation of the abstract method in the abstract class, unless the subclass is also an abstract class.

Example:

Action class:

package com.wmwx.oop.Demo08;

//Declare abstract classes using abstract
public abstract class Action {
    //Abstract method, only method name, no method body
    //Only as a constraint, expect others to achieve
    public abstract void doSomething();
}

Class A:

package com.wmwx.oop.Demo08;

public class A extends Action{
    //The subclass must implement the abstract method of the parent class
    //Unless the subclass is an abstract class
    @Override
    public void doSomething() {

    }
}

Interface

Interface is an abstract type and a collection of abstract methods in JAVA programming language. It is usually declared as interface. The basic syntax is as follows:

[Access modifier ] interface Interface name [extends Other interface names] {
        // Abstract method
}

Characteristics of interface:

  • Every method in the interface is implicitly abstract. The methods in the interface will be implicitly specified as public abstract, and can only be public abstract.
  • The interface can contain variables, but the variables in the interface will be implicitly specified as public static final, and can only be public static final.
  • The methods in the interface cannot be implemented in the interface. Only the classes that implement the interface can implement the methods in the interface.
  • An interface can inherit from another interface. Use the extends keyword The child interface inherits the methods of the parent interface.

When a class implements an interface, it needs to implement all the methods in the interface. Otherwise, the class must be declared abstract. In Java, the implementation keyword is used to implement the interface, and its basic syntax is as follows:

class Class name implements Method name{
    //Implementing abstract methods in interfaces
}

Example:

UserService interface:

package com.wmwx.oop.Demo09;

//Define interface using keyword interface
public interface UserService {
    //All attributes in the interface are public static final
    //Generally, attributes are not defined in the interface
    int age = 60;

    //All methods in the interface are public abstract
    void add(String name);
    void delete(String name);
    void update(String name);
    void query(String name);
}

TimeService interface:

package com.wmwx.oop.Demo09;

public interface TimeService {
    void timer();
}

UserServiceImpl class:

package com.wmwx.oop.Demo09;

//Class uses the keyword implements to implement the interface
//The class that implements the interface needs to override all methods of the interface
//A class can implement multiple interfaces
public class UserServiceImpl implements UserService, TimeService{

    @Override
    public void add(String name) {

    }

    @Override
    public void delete(String name) {

    }

    @Override
    public void update(String name) {

    }

    @Override
    public void query(String name) {

    }

    @Override
    public void timer() {

    }
}

Inner class

The so-called internal class is to define another class inside a class.

Example:

Outer class:

package com.wmwx.oop.Demo10;

//External class
public class Outer {
    private int id=10;
    public void out(){
        System.out.println("This is the method of the external class!");
    }

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

        //Get the private properties of the external class
        public int getId(){
            return id;
        }
    }

    public void method(){
        //Local inner class, in the method of outer class
        class Inner{

        }
    }
}

//A java file can have multiple classes, but only one public class
class A{

}

Application class:

package com.wmwx.oop;

import com.wmwx.oop.Demo09.UserService;
import com.wmwx.oop.Demo10.Outer;

//Startup class
public class Application {
    public static void main(String[] args) {
        //The external class uses the new keyword
        Outer outer = new Outer();
        outer.out();
        //Inner classes are instantiated by outer classes
        Outer.Inner inner = outer.new Inner();
        inner.in();
        System.out.println(inner.getId());
        //Anonymous class, without saving instances to variables
        new Outer().out();
        //Implementing interfaces using anonymous classes
        UserService userService = new UserService() {
            @Override
            public void add(String name) {

            }

            @Override
            public void delete(String name) {

            }

            @Override
            public void update(String name) {

            }

            @Override
            public void query(String name) {

            }
        }
    }
}