What is object orientation?
In previous chapters, we have tended to design programs to solve problems by designing processes, or more precisely by “algorithms + data structures”. If you’re solving a simple problem, there’s no problem at all. However, in real life, people’s needs are always unpredictable, so it needs a more reusable way to design programs, at this time, OOP(Object-oriented Programming) is the Object oriented way to shine. OOP is not the exclusive domain of the Java language. You can see the shadow of object orientation in other languages as well. C#, TypeScript, C++ are all classic object-oriented programming languages. In the object-oriented world, programs are composed of objects, and tasks are done through messages between objects.
What exactly is the object?
This is a big topic, so here are some basic concepts.
- To describe an object, you start with a modeled template, which in Java is called a class. Most objects are abstractions from real life, such as time-related operations. In object-oriented, there is a corresponding class :Date
- A class is a template for an object, an object is an instance of a class, and the relationship here is just like – everyone has a name and an ID card, but everyone has a name and an ID card, so the relationship between “people” and “zhang SAN” is the relationship between class and object.
- Objects encapsulate data internally and communicate with externally provided methods. The representation of data is called state, and the method is the behavior of the object, through which the state of the object can be changed
Three basic principles of object orientation
encapsulation
Is easier to understand the concept of encapsulation, start with an example of life as an example, a TV set, internal may have a lot of complex structure and hardware design, then let the user directly to the operation of these internal parts can cause problems, so the manufacturer will provide a series of buttons, operate the TV remote control to let users better. It’s a process of encapsulation, where the details are hidden from the user, and the user just needs to know what I can achieve with this button. This is what happens in a program: when I call a method of a utility class, it gives me what I need to input.
inheritance
Inheritance is for better extension and reuse. Through inheritance, you can directly obtain all the capabilities of the extended class (usually called the parent class), so as to avoid repetitive work; Inheritance also means that the set of objects has some of the same characteristics, so their “types” are the same.
In Java, for example, you’ll often see something like this.
User person = new Person();
Copy the code
Java supports only single inheritance.
polymorphism
Polymorphic modes can take on many different forms:
- Different objects have different behaviors for the same message, which is represented in Java as overriding Override.
- Methods with the same name can be distinguished by different parameters. Different methods can be invoked to match corresponding methods. This is where overloading comes in.
To quote from Ideas for Java Programming, a program that sends a message to an object without knowing exactly what type it is receiving but ultimately executes correctly is “Polymorphism” of the object. Object – oriented programming languages implement object polymorphism by means of “dynamic binding”.
Relationships between classes
- Uses-a: a method of class A manipulates an object of another class, so the function of class A depends on B. The program should minimize the dependency between classes and reduce the degree of coupling between classes.
- Has-a: Class A holds class B as its members, such as a User class that holds a set of roles. This is the aggregation relation.
public class User{
/** * Role list */
private List<Role> roles;
}
Copy the code
- Is-a: inheritance relationship. For example, class A inherits from class B.
What are Java objects?
When you talk about objects in Java, you have to talk about classes. To produce an object, we first have to describe a template, just like in the factory, we want to make a mobile phone case, so we first have to design a mold, and then according to this mold processing mobile phone case. The same is true for relationships between classes and objects: a class can describe the characteristics of an object: for example, a field(member variable), a constructor constructor, a method method, a class-type. In the program, the constructor can be triggered by the new keyword to obtain an object, and the state of the object can be changed by calling the method.
New and constructor
To produce an object using the new keyword, the constructor method is automatically triggered during the new process. Among them, the construction method is summarized as follows:
- The constructor method is the same as the class name.
- A class can declare more than one constructor method.
- The constructor approach supports polymorphism.
- The constructor method does not need to declare a return value.
- Collocative modifiers control the scope of use of constructor methods.
Let’s explain it in code:
- Define a user class
package com.tea.modules.model;
public class User/** * User name */private String userName;
/** * Password */
private String password;
/** * this is a constructor method */
public User(a){
System.out.println("A User object was created."); }}Copy the code
- The production object
User user = new User();
Copy the code
- Result
Here we verify that the constructor method is automatically triggered when new is used to produce an object instance, a process also known as initialization.
- If you declare an object directly, you only get a pointer
Error model
User user;
System.out.println(user.toString());
Copy the code
No parameter constructor
When defining a Java class, if you don’t need to customize the object creation process, you don’t have to write a constructor method at all. The compiler will automatically create a constructor for you that takes no arguments. If the constructor is explicitly declared, the compiler will not create it for you.
static
Methods decorated static represent static methods that do not belong to an object, but to a class. Defining static initializers on a class is usually done only once, because after loading the class (the template of the object), you can produce objects directly from the template. In other words, to get a User object, you must first load a user.class.
Static methods cannot be called with the this keyword and use the class name. Method “.
// Static method
Math.pow(1.2);
Copy the code
What did the bottom layer do at new?
To get a better idea of this, we declare the age property of the User class as int(although this is not recommended in practice), and here I use Lombok to override the toString method for automatic generation.
- User.class
package com.tea.modules.model;
import lombok.Data;
@Data
public class User {
private String userName;
private String password;
private int age;
static {
System.out.println("I'm a static method, I'm an event that happens when the class loads.");
}
{
System.out.println("I'm a method that executes at initialization, and I have precedence over the constructor.");
}
public User(a){
System.out.println("A User object was created."); }}Copy the code
- Test
package com.tea.modules.java8.oop;
import com.tea.modules.model.User;
/** * Understand object-oriented thinking - object constructors and initializers *@author jaymin
* @since2021/4/10 16:15 * /
public class OOPDemo {
public static void main(String[] args) {
User user = newUser(); System.out.println(user.toString()); }}Copy the code
- Result
- View the compiled instructions
To solve this problem, you can use javap -c oopdemo.class to view the JVM’s compiled instruction set.
- General process of new
- We know that to produce an object we need to find a class, and the Java class we define will eventually compile into one
.class
File. The JVM first loads this file into memory and gets oneUser.class
Object. - Execution is
static
Modified code block. - perform
new
Keyword to allocate memory for the current object. - Sets all fields in the object to zero (the reference type to null and the underlying type to default, such as int to 0).
- Executes the code block, the initialization action at the field definition.
- Execute the constructor method.
- You get a reference to an object.
- graphic
The new keyword is simple
“JVM” – Object initialization