On Java object oriented

Introduction to the author

Author name: Ming Shiyin in programming world
Introduction: CSDN blog expert has been engaged in software development for many years and is proficient in Java and JavaScript. Bloggers also learn and grow step by step from scratch, know the importance of learning and accumulation, and like to fight and upgrade with ADC. Welcome to pay attention and look forward to learning, growing and taking off with you!

Popular column recommendation

[1] Java games (Tetris, aircraft war, plant war, zombie, etc.)
[2] JavaWeb project practice (library management, online examination, dormitory management, etc.)
[3] Wonderful examples of JavaScript (aircraft war, snake, verification code, etc.)
[4] Introduction to Java Xiaobai 200 cases
[5] Learn Java from scratch and be interested in learning Java
[6] Idea from zero to mastery

introduction:

A small partner in the group asked me to write an article about object-oriented. At first, I didn't directly agree. One is that I'm a little busy recently. The other is that I'm afraid I can't write well. After all, object-oriented involves a wide range of contents.
I have been brewing for several days before writing this article. I hope it will help my friends understand object-oriented. I also hope that my fan friend can get the knowledge he wants from this article.

Process oriented and object-oriented description

Process oriented is to analyze the steps to solve the problem, then implement them step by step, and then call them one by one.
Object oriented is to decompose solving problems into multiple objects, and objects are a kind of behavior to describe and deal with some problems.

Such a simple description must be a little confused. Here are some examples in life to illustrate.

Process oriented and object-oriented examples

Example in life: do you want to eat navel orange
Process oriented example:

Go out – > take the car – > supermarket – > choose navel oranges – > pay – > take the car home – > take out navel oranges – > peel navel oranges – > eat navel oranges – > wash your hands.

Here is a brief description of the process from buying navel orange to eating navel orange. Process oriented is to realize each step above in different ways.

Object oriented example:
Object oriented design solves the problem from another idea, as follows:

I want to eat navel orange – > girlfriend brings the navel orange to you – > eat it. Finish

Analyze what your girlfriend should do:

Go out – > take the car – > supermarket – > choose navel oranges – > pay – > take the car home – > take out navel oranges – > peel navel oranges – > feed you – > wash your hands.

There must be a little partner who said that there is no difference between you and process oriented. This is an action, which is just divided into two people to complete, without reducing or optimizing anything.
On the surface, it does look like this, but we can look at the essence through the problem:

  1. For the role of "you", do you just need to say that I want to eat oranges (call methods) and then open my mouth to eat? This is undoubtedly an optimization. If there is no girlfriend (object), do you have this benefit?
  2. For the role of "girlfriend", can she only give you this benefit? Of course not. If one day she is not your object, but someone else's object, and someone says "I want to eat oranges", can he also use this benefit? In other words, the object "girlfriend" has a method called "eat oranges for her boyfriend". Can her boyfriend call it.
  3. If you are still process oriented (single) and you want an navel orange, you can only repeat the following process:

Go out – > take the car – > supermarket – > choose navel oranges – > pay – > take the car home – > take out navel oranges – > peel navel oranges – > eat navel oranges – > wash your hands and start over.

  1. Similarly, object-oriented, as long as you call the "I want to eat navel orange" method for reuse, you don't need to care about what the method is doing. Of course, the "girlfriend" object can also be reused. If the object is switched, the "eat navel orange" method is encapsulated and won't disappear, and others can call it.

So brother Ming, I asked you, do you understand? If you don't understand, I have no choice.

Object definition

Object is a concrete entity with clearly defined state and behavior. It is the core of object-oriented programming. It is used to describe entities in the real world, provide entity basis for computer applications, and is also a package to complete specific tasks.

Three characteristics of object oriented

encapsulation

Encapsulation is one of the features of object-oriented and the main feature of object and class concepts.
Encapsulation is to encapsulate objective things into abstract classes, and classes can only allow trusted classes or objects to operate their own data and methods, and hide information from untrusted ones.

Generally speaking, your girlfriend calls the "I want to eat navel orange" method. You can eat navel orange, and others can call the "I want to eat navel orange" method of his girlfriend object. Can you call the "I want to eat navel orange" method of "other people's" girlfriend "? The answer is obviously No.

In other words, a class is an abstract collection, where "girlfriend" is abstracted into a class.

The object is an independent individual, such as your girlfriend and his girlfriend; They are "girlfriends", but they are independent of each other.

Code example

  1. Create a "girlfriend" class
public class GirlFriend {
	String name;//name
	int age;//Age
}

Test:

public class Test {

	public static void main(String[] args) {
		GirlFriend girlFriend = new GirlFriend();
		girlFriend.name="Cai Wenji";
		System.out.println("my girlfriend:"+girlFriend.name);
	}
}

Operation results:

My girlfriend: Cai Wenji

  1. Encapsulation of member properties
    In the above example, the two member attributes, name and age, are not restricted, so they can be used directly in the test class (assignment and value), but in fact, generally speaking, the member attribute is restricted and private is added to the member attribute.
public class GirlFriend {
	private String name;//name
	private int age;//Age
}

Now let's look at the test class. It is an error

So we can encapsulate the assignment and value into methods.

  1. Value taking method and assignment method
    Member properties are private and methods are public.
public class GirlFriend {
	private String name;//name
	private int age;//Age
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

Test call:

public class Test {

	public static void main(String[] args) {
		GirlFriend girlFriend = new GirlFriend();
		//girlFriend.name = "Cai Wenji";
		//System.out.println("my girlfriend:" + girlFriend.name);
		girlFriend.setName("Cai Wenji");
		girlFriend.setAge(18);;
		System.out.println("my girlfriend:"+girlFriend.getName()+","+girlFriend.getAge()+"year");
	}
}

Call:

My girlfriend: Cai Wenji, 18 years old

  1. Construction method assignment
	public GirlFriend(String name,int age){
		this.name=name;
		this.age=age;
	}

Test code

public class Test {

	public static void main(String[] args) {
		GirlFriend girlFriend = new GirlFriend("Cai Wenji",18);
//		girlFriend.setName("Cai Wenji");
//		girlFriend.setAge(18);
		System.out.println("my girlfriend:"+girlFriend.getName()+","+girlFriend.getAge()+"year");
	}
}

Operation results:

My girlfriend: Cai Wenji, 18 years old

  1. Affiliation of joining objects
    Why should we add the attribution of objects? Because classes are abstract and objects are independent one by one, we can't all "girlfriends" are Cai Wenji. Isn't this a mess? Moreover, once an object is created using new in java, the object is an independent individual.

Girlfriendgirlfriend = new girlfriend ("Cai Wenji", 18);

All use the above code to create a girlFriend, but each time it is not the same "girlFriend".

Verify the code:

public class Test {

	public static void main(String[] args) {
	/*	GirlFriend girlFriend = new GirlFriend("Cai Wenji ", 18);
//		girlFriend.setName("Cai Wenji ");
//		girlFriend.setAge(18);
		System.out.println("My girlfriend: "+ girlFriend.getName() +", "+ girlFriend.getAge() +" year old ");
		*/
		GirlFriend girlFriend = new GirlFriend("Cai Wenji",18);
		GirlFriend girlFriend1 = new GirlFriend("Cai Wenji",18);
		
		System.out.println(girlFriend.hashCode());
		System.out.println(girlFriend1.hashCode());
	}
}

Operation results:

366712642
1829164700

As can be seen from the output, it is not the same object. I can change it as follows:

public class GirlFriend {
	private String name;// name
	private int age;// Age
	private String manName;// Man's name

	public String getManName() {
		return manName;
	}

	public void setManName(String manName) {
		this.manName = manName;
	}

	public GirlFriend(String name, int age,String manName) {
		this.name = name;
		this.age = age;
		this.manName = manName;
	}

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

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

Test code:

public class Test {

	public static void main(String[] args) {
		GirlFriend girlFriend = new GirlFriend("Cai Wenji",18,"I");
		GirlFriend girlFriend1 = new GirlFriend("Yao",19,"you");
		
		System.out.println(girlFriend.getManName()+"My girlfriend:"+girlFriend.getName()+","+girlFriend.getAge()+"year");
		System.out.println(girlFriend1.getManName()+"My girlfriend:"+girlFriend1.getName()+","+girlFriend1.getAge()+"year");
	}
}

Operation results:

My girlfriend: Cai Wenji, 18 years old
Your girlfriend: Yao, 19

Benefits of encapsulation

  1. Improved data security
    For private member properties: others cannot modify them by means of variable name and property name.
  2. Easier to use
    After encapsulation, multiple callers get the object when they are in use, and then call the corresponding method.
  3. Hiding is realized
    The implementation process is invisible to the caller. The caller only needs to call the method and does not know the specific implementation process.

As in the previous example, you don't need to care how your girlfriend gets you oranges. You just tell her I want to eat oranges, and then wait for her to feed you oranges.

inherit

summary

Inheritance mechanism is an indispensable key concept in object-oriented programming, the foundation of software reusability, and the main way to improve the scalability and maintainability of software system.
In Java, the inherited class is called the parent class, also called the base class; the inherited class is called the subclass, also known as the derived class or super class; inheritance is the most significant feature of object-oriented. Inheritance is to derive a new class from an existing class, which can inherit the data properties and behavior of the existing class. Of course, subclasses can also extend their own new capabilities.

Generally speaking, each of us has inherited a lot of abilities from our parents, such as eating, drinking, talking, walking, thinking, etc. we can also expand our abilities, such as learning programming and playing the king (off the topic).

In Java, the following syntax is used to implement the inherited relationship:

Class subclass extends parent class {}

Code explanation

  1. Inherited member variables
public class Test {

	public static void main(String[] args) {
		Student student = new Student();
		System.out.println(student.age);
	}
}

class Human {
	int age = 20;//Age
}
class Student extends Human{
	
}

Operation results:

20

You can see that the age attribute is inherited, but if the age is declared private, it cannot be inherited.

  1. Inherited member method
public class Test {

	public static void main(String[] args) {
		Student student = new Student();
		student.study();
	}
}

class Human {
	int age = 20;//Age
	
	void study(){
		System.out.println("Learning skills");
	}
}
class Student extends Human{
	
}

Operation results:

Learning skills

Of course, you cannot inherit member methods whose parent class is declared private.

  1. rewrite
    Rewriting is to let the subclass have its own implementation. Of course, the formal parameters and return values cannot be changed. You can modify the implementation code in the subclass.
public class Test {

	public static void main(String[] args) {
		Student student = new Student();
		student.study();
	}
}

class Human {
	int age = 20;//Age
	
	void study(){
		System.out.println("Learning skills");
	}
}
class Student extends Human{
	@Override
	void study(){
		System.out.println("Learning knowledge in school");
	}
}

Operation results:

Learning knowledge in school

  1. super keyword
public class Test {

	public static void main(String[] args) {
		Student student = new Student();
		student.study();
		student.pStudy();
		
	}
}

class Human {
	int age = 20;//Age
	
	void study(){
		System.out.println("Human learning skills");
	}
}
class Student extends Human{
	@Override
	void study(){
		System.out.println("Learning knowledge in school");
	}
	
	void pStudy(){
		super.study();
	}
}

Operation results:

Learning knowledge in school
Human learning skills

The usage of super keyword is as follows:

1. super can be used to reference the instance variable of the direct parent class.
2. super can be used to call direct parent methods.
3. super() can be used to call the direct parent constructor.

This only shows that super can directly call the parent class, and other uses are similar.

polymorphic

concept

The so-called polymorphism refers to the specific type pointed to by the reference variable defined in the program and the method call issued through the reference variable. It is not determined during programming, but only during program operation, that is, a reference variable will point to the instance object of which class, and the method call issued by the reference variable must be implemented in which class during program operation Period can be determined.

Polymorphism is the ability of the same behavior to have multiple different forms or forms.

Code explanation

public class Test {

	public static void main(String[] args) {
		Human h = new Student();
		h.study();	
	}
}

class Human {
	int age = 20;//Age
	
	void study(){
		System.out.println("Human learning skills");
	}
}
class Student extends Human{
	@Override
	void study(){
		System.out.println("Learning knowledge in school");
	}
}

Operation results:

Learning knowledge in school

Maybe some little friends didn't understand it. Isn't this similar to the previous code?
In fact, the difference is here:

Human h = new Student();
h.study();

Here, the instance object is Student, but after it is transformed into Human, the study method is called through the Human instance object, but in fact, this h is the instance object of Student, and finally the study method of Student is called.

There are three necessary conditions for implementing polymorphism in Java:

Inheritance, rewriting and upward transformation.

Inheritance and rewriting have been met before this example;
Human h = new Student(); is the upward transformation;

Multiple subclass codes

public class Test {

	public static void main(String[] args) {
		//Upward transformation
		Human h = new Student();
		h.study();	
		//Upward transformation
		Human h1 = new Coder();
		h1.study();	
		//No upward transformation
		Human h2 = new Human();
		h2.study();	
	}
}

class Human {
	int age = 20;//Age
	
	void study(){
		System.out.println("Human learning skills");
	}
}
class Student extends Human{
	@Override
	void study(){
		System.out.println("Students learn knowledge at school");
	}
}

class Coder extends Human{
	@Override
	void study(){
		System.out.println("Programmers work overtime in the office to learn programming knowledge");
	}
}

Operation results:

Students learn knowledge at school
Programmers work overtime in the office to learn programming knowledge
Human learning skills

Looking at the above code, you can't tell their differences at compile time, but the results are very different at run time.

Why

You may ask, why do you do this? Inheritance, rewriting and upward transformation.
In fact, you will encounter the problem of program expansion in your work. For example, it is very convenient to add a new student of engineering here.

public class Test {

	public static void main(String[] args) {
		//Upward transformation
		Human h = new Student();
		h.study();	
		//Upward transformation
		Human h1 = new Coder();
		h1.study();	
		//No upward transformation
		Human h2 = new Human();
		h2.study();	
		
		Human h3 = new Builder();
		h3.study();	
		
	}
}

class Human {
	int age = 20;//Age
	
	void study(){
		System.out.println("Human learning skills");
	}
}
class Student extends Human{
	@Override
	void study(){
		System.out.println("Students learn knowledge at school");
	}
}

class Coder extends Human{
	@Override
	void study(){
		System.out.println("Programmers work overtime in the office to learn programming knowledge");
	}
}


class Builder extends Human{
	@Override
	void study(){
		System.out.println("Builders learn to build on the construction site");
	}
}

Such an extension is very convenient. There is no need to make any modification to the Student and Coder codes. In daily development, the Student and Coder codes are often very complex. An carelessness will lead to some errors, which will bring some trouble to our coding work.

Of course, polymorphism based on interface implementation is more common in work, and its principle is basically consistent with the above, which will not be explained here.
The above is my humble opinion. If you think it's OK, give brother Ming a third company!

Popular column recommendation

[1] Java games (Tetris, aircraft war, plant war, zombie, etc.)
[2] JavaWeb project practice (library management, online examination, dormitory management, etc.)
[3] Wonderful examples of JavaScript (aircraft war, snake, verification code, etc.)
[4] Introduction to Java Xiaobai 200 cases
[5] Learn Java from scratch and be interested in learning Java
[6] Idea from zero to mastery

Keywords: Java OOP

Added by Peredy on Wed, 08 Dec 2021 05:52:28 +0200