Four basic characteristics of java -- encapsulation inheritance polymorphism abstraction

Catch up tomorrow or may day c small long holiday, ready to write a few original articles in these days, for everyone to learn together.

First of all, let's have a good chat today. What are the features of java? How to use it? I believe there must be some Xiaobai who will be upset about it. It doesn't matter. Who hasn't come from that time! Next, I'll talk about my opinions step by step from diving to deep. Here's what I want to say

1. General

2. Concept understanding

3. Code example and analysis

4. Summary of personal experience

1. General

sequenceDiagram
 Encapsulation - > inheritance: four basic features of java
 Polymorphism > > abstraction: four basic features of java

2. Concept understanding

  • [1] Encapsulation:
-In object-oriented programming, Encapsulation refers to a method that packages and hides the implementation details of abstract function interface.
Encapsulation can be considered as a protective barrier to prevent code and data of this class from being randomly accessed by code defined by external classes.
To access the code and data of this class, strict interface control is necessary.
The main function of encapsulation is that we can modify our own implementation code without modifying the program fragments that call our code.
Appropriate encapsulation can make the code easier to understand and maintain, and also enhance the security of the code.
In fact, there are many examples in life. Let me make a few analogy,

For example: we all use QQ chat software, so if we want to use it, we must register first

When the registration is completed, next time we enter the password we set directly, no other operation is needed

This process is to encapsulate the data in QQ to prevent users from following

Only programmers can make changes, so that they can protect the security of the program

That is to say, the user doesn't need to wait until QQ is executed, how is it implemented internally, and hide the user
    There is another explanation: for example, a personal computer has many components - CPU memory, disk fan, etc 
    
    We don't need to know how the components are related to each other, as long as we know how their functions are implemented
    
    There are many examples in life that I won't tell you. (if you don't understand, you can leave a message in the private message or comment area)
  • [2] Inheritance
  • Inheritance,
Inheritance refers to the direct use of attributes and methods of another object by one object. In fact, many of the entities we encounter have the meaning of inheritance. For example, if a car is regarded as an entity, it can be divided into multiple sub entities, such as trucks, buses, etc. These version sub entities all have the characteristics of automobile, therefore, automobile is their "father", and these sub entities are the "children" of automobile (but children will also have their own new features). The subclass is the specialization of the parent class, that is, the instance (object) of the subclass must be the instance of the parent class, but the reverse is not necessarily true {for example, a circle must be a geometry, but the geometry in turn is not necessarily a circle! There will be many more
Let's also say a simple example: for example, the genealogy of your family is a very obvious inheritance relationship

If your father inherits your grandfather (that is, the child inherits the parent), then your father will certainly have the same characteristics as your grandfather, but! You will find that you have some characteristics that are different from your grandfather (and your grandmother, of course). You will have your own unique characteristics, which is the relationship of inheritance
  • [3] Polymorphism
-Concept: the same operation acts on different objects, can have different interpretations and produce different execution results, which is called polymorphism. Simply put: the reference of the parent class points to the object (variable) of the child class.

Reason: we know that encapsulation can hide implementation details and make code modular;

Inheritance can extend existing code modules (classes);
They are all for code reuse. In addition to code reusability, polymorphism can also solve the problem of tight coupling in projects and improve the scalability of programs.

Coupling degree refers to the correlation degree between module and code code. Through the analysis of the system, it is decomposed into a sub module, which provides a stable interface to reduce the coupling degree of the system. Module interface is used as much as possible to visit between module modules, rather than randomly referencing the member variables of other modules.

There are two advantages: 1. The application does not need to write function calls for each derived class, but only needs to process the abstract base class. Greatly improve the reusability of the program. //Inheritance 2. The function of the derived class can be called by the method or reference variable of the base class, which is called backward compatibility, which can improve the extensibility and maintainability. //The real function of polymorphism can be used in the parameters of a method and the return type of a method. (subclass variables refer to the variables of the parent class)
  • [4] Abstract:
It is to analyze each attribute of an object to replace the technique of expression.
To draw is to draw away; to look like. Expressed part
Like a tree. We know it's a tree at a glance, but why

In this way, we need to compare trees with other things in different places, which are abstracted.

Abstract things from the tree itself, it becomes meaningless, but the combination of 100 is the concept of tree.

For example, a tree, 10 meters high, has rough bark, needle shaped leaves, straight trunk, and so on. These attributes combine to feel like a pine tree. But if I say 10 meters alone, I don't know what I mean if I don't have an object.

Abstract object is a very useful method in programming. It can correspond boring data with single object, which is easy to understand and easy to program.

For example, in the preparation of student management system.

The definition of students should first have a name, then a gender, then a student number, and so on. These are abstract properties

3. Code example and analysis

  • [1] Polymorphism
public class Main {
    public static void main(String[] args) {
        // To tax a small partner with ordinary income, wage income and special allowance of the State Council:
        Income[] incomes = new Income[] {
            new Income(3000),
            new Salary(7500),
            new StateCouncilSpecialAllowance(15000)
        };
        System.out.println(totalTax(incomes));
    }

    public static double totalTax(Income... incomes) {
        double total = 0;
        for (Income income: incomes) {
            total = total + income.getTax();
        }
        return total;
    }
}

class Income {
    protected double income;
//Construction method
    public Income(double income) {
        this.income = income;
    }
//Define a method
    public double getTax() {
        return income * 0.1; // Tax rate 10%
    }
}
//The child class Salary inherits the parent class Income
class Salary extends Income {
	//Construction method
    public Salary(double income) {
    	//super calls the constructor in the inherited Salary
        super(income);
    }

    @Override
    public double getTax() {
        if (income <= 5000) {
            return 0;
        }
        return (income - 5000) * 0.2;
    }
}

class StateCouncilSpecialAllowance extends Income {
    public StateCouncilSpecialAllowance(double income) {
        super(income);
    }

    @Override
    public double getTax() {
        return 0;
    }
}

//Output: 800.0

Observe the totalTax() method: using polymorphism, totalTax() only needs to deal with income. It doesn't need to know the existence of StateCouncil special allowance and sales to fully calculate the tax. If we want to increase the income of a kind of contribution, we only need to derive it from income, and then correctly overwrite getTax method (), and pass the new type to getTax()
, no need to re modify the code

It can be seen that polymorphism is such a powerful function that more types of subclasses are allowed to be added to realize function extension without modifying the code based on the parent class

  • [2] Inheritance
public class Bike {
	int speed;
	int brand;
	int colornum;
	//Construction method
	Bike(){
		System.out.println(" call bike constructor");
	}
	public void speedUp() {
		speed = 0;
		System.out.println(" too slow");
	}
	public void presshorn() {
		System.out.println(" I am riding the bike");
	}
}

public class SpeedBike extends Bike{
	/**
	 * super Data members and their constructors can be called
	 */
	SpeedBike(){//Construction method of subclass
		super();
		super.colornum=12;//Subclass call data member
		super.presshorn();
		System.out.println("call bike construction");	
	}
	public void ride() {
		System.out.println("I am riding the bike");
	}
	/**
	 * super Methods of the parent class can be called
	 */
	public void speedUp() {
		super.speedUp();
		speed+=10;
		System.out.println("so fasyt! ," + " my speed is " + speed + " now");
	}
}

public class DemoBike{
	public static void main(String[] args) {
		SpeedBike aride = new SpeedBike();
				aride.presshorn();
				aride.speedUp();
				aride.ride();
	}
}

//Output:
call bike constructor
 I am riding the bike
call bike construction
 I am riding the bike
 too slow
so fasyt! , my speed is 10 now(This output code overrides the methods that override the parent class)
I am riding the bike

  • [3] Abstraction
    If a class defines a method but does not have specific execution code, it is an abstract method. Abstract methods are implemented by abstract. Because abstract methods cannot be executed, this class must be applied as an abstract class

For example, if the Person class defines the abstract method run(), then the run() method must be overridden when implementing the subclass Student

public class Main {

	public static void main(String[] args) {
		Person p= new Student();
		p.run();
	}
}
abstract class  Person() {
	public abstract void run();
}
class Student extends Person{
	@overriding
	public void run() {
		System.out.println("Student . run");
	}
}

  • [4] Encapsulation
package com.fengzhuang;
class Car{
    private String name;//Private member, name
    private String color;//Private members, color
    private String size;//Private member, size 
    //Get the method of String type name, and return to
    public String getName(){
        return name;
    }
    public String getColor(){
        return color;
    }
    public String getSize(){
        return size;
    }
    //Because the method name and parameter name are the same, this is used
    public void setName(String name){
        this.name=name;
    }
    public void setColor(String color){
    this.color=color;
    }
    public void setSize(String size){
    this.size=size;
    }
}

package com.fengzhuang;
public class Test{
    public static void main(String[] args){
        Car b=new Car();//Instantiation operation
        b.setName("BMW");//assignment
        b.setColor("Red");
        b.setSize("large");
        //It's clear that these processes don't see how they can be implemented.
        String name=b.getName();//Value
        String color=b.getColor();
        String size=b.getSize();
        //Final output
        System.out.println(name+":"+color+":"+size);
    }
}

//Output:
//BMW: Red: Large

Resolution: since we have set several of them as private variables when we access the name variables, we can only access them through the set builder if we want to access it

4. Summary of personal experience

I've already said so, so let me say one last point and summarize these!

The advantage of encapsulation is that the definition can only operate on the attributes inside the class, and the attributes cannot be manipulated outside. To modify these attributes, you can only use the encapsulation method defined by you;
Inheritance reduces the redundancy of code and omits a lot of duplicate code. Developers can define the properties and methods that all subclasses must have from the bottom of the parent class to achieve the purpose of coupling;
Polymorphism realizes the personalization of methods. Different subclasses can implement different methods according to specific conditions. The method defined by the parent class is not flexible enough, so it is insufficient to meet special conditions

These are my understanding of these. I hope it can help you. ——All in all, this is really very important. It's the java language! You must understand, ponder, write code and think more. Naturally, it will not be difficult, just like the principle of "it will not be difficult if it is met, it will not be difficult if it is difficult". On the one hand, this article is written to record some knowledge at once. On the other hand, it is hoped that it can help those friends who have a little knowledge of these concepts and the use of code to create this article Zhang is really not easy to write for a long time. I hope you can support me a lot. If you don't understand, you can send me a private letter or comment underground. When you see it, I will try my best to solve it for you. Let's learn together. (in addition, I will continue to publish some original articles tomorrow and the day after tomorrow. If you think what I wrote is helpful to you, you can pay attention to me for a while, which is convenient for searching.)

Everyone support!

Keywords: Java Programming Attribute

Added by Alanmoss on Mon, 04 May 2020 18:39:42 +0300