What is object-oriented, its three basic features: encapsulation, inheritance, polymorphism

What is object-oriented thinking? It's very common to have learned java and really don't know how to explain to others what object-oriented means. Let us review this fantastic idea together~


1. Object-oriented and process-oriented

Now more and more high-level languages ​​are becoming popular, such as the familiar c++, python, java, etc., these are all based on the 面向对象language
and the most basic language that must be learned in schools - the c language belongs 面向过程to language.
Ok, now let's discuss the difference between these two types of languages

1. What is process-oriented?

Process-oriented:
It is to analyze the steps needed to solve the problem, and then use functions to realize these steps step by step. When using them, they can be called one by one.

For example, how many steps does it take for an elephant to fit in a refrigerator?
insert image description here
According to the process-oriented thinking:
Step 1: The staff goes to open the refrigerator door
Step 2: Stuff the elephant into the refrigerator
Step 3: The staff closes the refrigerator door
Hey, we can see it here,Process-oriented is to realize one thing step by step
expressed in code

    public void openDoor(){
    
    }  //开门
    public void putIn(){
    
    }       //装冰箱
    public void closeDoor(){
    
    }   //关门

Calling these methods in turn is complete

2. What is object-oriented?

The object is the abstraction of the things in the question.
Object-oriented:
it is to abstract all the things in reality into "objects". Each object is unique and can have its properties and behaviors. We can solve the problem by calling the methods and properties of these objects.

Use object-oriented thinking to solve the problem of putting elephants into refrigerators

A general understanding of the concept of objects can be said to be a kind of understanding of real things 抽象映射.
insert image description here
For example in this event:
refrigerator as an object;
elephant as an object.
The refrigerator has these functions: open the door, load objects, close the door

class fridge{
    
    
    public void open(大象){
    
    }   //开门
    public void putIn(大象){
    
    }  //放进冰箱
    public void close(大象){
    
    }  //关门
}
class elephant{
    
    
	public void eat(){
    
    }   //吃
}

What do you see? Each object is independent and has its own functions. You only need to concentrate on realizing your own functions. Therefore, in the stage of establishing the object model, only focus on the functions of the object, but do not consider how to realize these functions.

The benefits of object-oriented include good extensibility. For example, I have given an eating function to the elephant, and it can eat in the refrigerator by calling it.Object-oriented is to abstract real problems into objects, and solve problems by calling the properties or functions of each object.

If I want to modify my requirements and change the elephant to a rabbit, do I have to change the elephant in each step to a rabbit when I use process-oriented. And with object-oriented solutions, I can even recreate a rabbit object, just select the rabbit when calling.

2. The relationship between classes and objects

Many people will create objects, isn't it just newthat, isn't it just to call object methods new.方法. As a result, some people subconsciously regard the class as an object when they are in the new class, so is the class an object?

Certainly not, first give their basic concepts

1. Basic concepts

Object
An object is a package composed of data (describing the attributes of things) and operations on the data (reflecting the behavior of things). It describes an entity of objective things and is the basic unit of the system.

Class A
class is the definition of a group of objects with the same data and the same operations. It is the template of the object, and the methods and data it contains describe the common behavior and attributes of a group of objects. A class is an abstraction above an object, and an object is the embodiment of a class, an instance of a class. A class can have its subclasses, as well as other classes, forming a class hierarchy.

2. The difference between class and object

1) A class is an abstraction of an object, and an object is a concrete instance of a class. Classes are abstract and take up no memory, while objects are concrete and take up storage space.

2) A class is an abstraction of a group of objects with the same properties and behavior. We can think of a class as a blueprint for creating an object , and the object implements something according to this blueprint.

For example, given a blueprint of an "umbrella", we have designed a sunny umbrella, a sword umbrella, etc., and you will find that these umbrellas all have the same behavior----to block the rain .
insert image description here

Therefore, the instantiation result of a class is an object, and the abstraction of a class of objects is a class, which describes a group of objects with the same attributes and methods.

3. Basic features: encapsulation, inheritance, polymorphism

1. Packaging

(1) Basic concepts
Encapsulation (encapsulation) is information concealment. It means that when determining the content of a certain part of the system, it should be considered that the information and connections of other parts are carried out inside this part, and the information connection between external parts should be as little as possible.

(2) Four access control levels

  • public: open to the public, with the highest access level
  • protected: Only exposed to classes or subclasses in the same package
  • Default: only exposed to classes in the same package
  • private: not open to the public, can only be accessed inside the object, with the lowest access level
    insert image description here

(3) Encapsulation and use
1. Hide as many things as possible, and improve the simple interface to the outside world
. For example, there are semi-automatic washing machines and a fully automatic washing machine.

The interface of the semi-automatic washing machine has the following methods:
① start
② shut down
③ release water
④ timing
⑤ wash
⑥ drain
⑦ dehydrate

The fully automatic washing machine has the following methods
: 1. Turn on
2. Shut down
3. Set the washing machine mode
4. Start washing clothes and turn off automatically after washing

By comparison, we will find that the automatic washing machine encapsulates the details of water discharge, timing, washing, draining, dehydration , etc. convenient.

2. Hide all attributes
Add a certain attribute to allow external access, then provide a public method to access this attribute. If the dog class has a name and age attributes, the outside world is not allowed to directly access the attributes, but it is allowed to provide get and set methods to access

class Dogs{
    
    
    private String name;  //名字
    private String age;   //年龄
    
    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getAge() {
    
    
        return age;
    }

    public void setAge(String age) {
    
    
        this.age = age;
    }
}

Then we set the property as private, and set the method of setting the property to the outside world as public.

Some people may ask, since it is open to the public, why not directly set the name and age attributes to public, but instead set them through methods, will it be superfluous?

No, for four reasons:

(1) In line with the objective law that the external cause works through the internal cause
Assume that the original dog has a name called "Wangcai", which was given by the original owner of the object itself, and the setName() method [internal cause] is called. Well, the owner who adopted the dog plans to change the dog's name to "Rhubarb". He is the user and calls the setName() method [external cause].

(2) Flexible control of the access level for reading and modifying attributes
For example, I can only let users know the dog's name, but they are not allowed to modify him. Then set setName() to private and getName() to public.

(3) Prevent users from modifying attributes by mistake
Directly call the attributes of the class, what should I do if I make a mistake. So we can add restrictions in the public method setName() to prevent users from modifying attributes by mistake. For example, the dog's age should range from 0 to 20.

public void setAge(int age) {
    
    
    if (age >20 || age < 0){
    
    
        throw new IllegalArgumentException("口令不合法");
    }
    else {
    
    
        this.age = age;
    }
}

(4) Contribute to object encapsulation and implementation details.
If we do not want to disclose the process of judging the legal age above to the user, we will encapsulate this process in a "transparent" method with private. This process of judging legal age is transparent to the user.

A concept that has the same meaning as encapsulation is transparency. The object encapsulates the implementation details, which means that the implementation details of the object are transparent to the user. Transparency is understood here as "invisible"

public void setAge(int age) {
    
    
        isLegal();   //判断是否合法
        this.age = age;
    }

private void isLegal(){
    
    
    if (age >20 || age < 0){
    
    
        throw new IllegalArgumentException("口令不合法");
    }
    else return;
}

2. Inheritance

Inheritance: Let an object of one type acquire the properties and methods of an object of another type. Inheritance means that the subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance fields and methods of the parent class, or the subclass inherits the methods from the parent class, so that the subclass has the same behavior as the parent class.

(1) Grammar

class A extends B{}

What did you inherit in total? There are two cases

  • When A and B are in the same package, A inherits the member variables and member methods of public, protected and default access levels in B
  • When A and B are not in the same package, A inherits the public and protected member variables and member methods in B

(2) Inherit the parent class member variable/method
hanqishi inherits the parent class Dog

class Dog{
    
    
    public String name="小白";
    public void say(){
    
    
        System.out.println("汪汪汪");
    }
}
//哈奇士
class haqishi extends Dog {
    
    
    public void test(){
    
    
        System.out.println(name);
        say();
    }
}

Call haqishi's test() method, the test is as follows

Xiaobai
woof woof

Test results: The subclass haqishi inherits the member variables and member methods of the parent class

(3) Rewrite the parent class method
The subclass haqishi rewrites the say method of the parent class Dog

class Dog{
    
    
    public String name="小白";
    public void say(){
    
    
        System.out.println("汪汪汪");
    }
}
//哈奇士
class haqishi extends Dog {
    
    
    @Override
    public void say() {
    
    
        //super.say();    继承父类原有方法
        System.out.println("哈哈哈");
    }
}

Call the subclass say method, the test is as follows:

Hahaha

(4) Overloading the parent class method
The overloading method must meet the following conditions:
1. The method name is the same
2. The parameter type, number, and order of the method are at least one different.
3. The return type of the method can be different
4. The modifier of the method can be different

class Dog{
    
    
    public String name="小白";
    public void say(){
    
    
        System.out.println("汪汪汪");
    }
}
//哈奇士
class haqishi extends Dog {
    
    
   //重载 改变参数
    public void say(String name) {
    
    
        System.out.println(name+"汪汪汪");
    }
	//重载 改变参数+返回值
    public int say(int age) {
    
    
        System.out.println("汪汪汪"+age);
        return age;
    }
}

Call
haqishi h = new haqishi();
h.say();
h.say("Haqishi");
h.say(6);
the results are as follows:

woof woof
woof woof
woof woof woof 6

3. Polymorphism

Polymorphism: For the same behavior, different subclass objects have different manifestations. There are 3 conditions for the existence of polymorphism:
1) Inheritance 2) Rewriting 3) The parent class reference points to the subclass object.

public class extend {
    
    
    public static void main(String[] args) {
    
    
        Animal a = new Dog();
        Animal b = new Cat();
        a.say();
        b.say();
    }
}

abstract class Animal {
    
    
    abstract void say();
}
//猫
class Cat extends Animal{
    
    
    public String name="小黑";
    public void say(){
    
    
        System.out.println("喵喵喵");
    }
}
//狗
class Dog extends Animal{
    
    
    public String name="小白";
    public void say(){
    
    
        System.out.println("汪汪汪");
    }
}

operation result

woof woof meow
meow meow

Understand polymorphism
In this running environment, the specific type pointed to by the reference variable and the method call issued through the reference variable are not determined during programming, but are determined during the running of the program. The Java virtual machine calls the specified method of the object according to the object pointed to by the reference variable. This operation mechanism is called动态绑定

References: "Java Object-Oriented Programming (Second Edition)" - Sun Weiqin

Guess you like

Origin blog.csdn.net/weixin_51201930/article/details/122652397