Classes and objects
1. Process oriented and object oriented
When I started to learn programming in my freshman year, my teacher said that I must understand process oriented development and object oriented development.
I thought to myself, “What else can the school assign me? Let me face her every day?” Turns out I was overthinking it.
So I subconsciously went to Baidu: what is object oriented?
I found baidu’s explanations to be the same as those of my college teachers: inscrutable and unintelligible.
Later, MY head cantilever cone stab unit to learn, finally understand.
I’m going to tell you the difference with a simple case study.
Case 1: King of Glory
Process-oriented:
-
- Open the Honor of Kings app
-
- Login account
-
- Choose game mode 5V5
-
- Choose a hero
-
- Start the game
-
- Game over
Object-oriented:
-
- Create three objects: people, mobile, and Honor of Kings
-
- Add method to human object: open mobile phone, operation king of Glory
-
- Added method to mobile object: Run Honor of Kings
-
- Added methods to King of Glory objects: Login, set game mode, set heroes, runes, start the game, decide whether to win or lose the game, etc.
-
- People turn on their phones
-
- Running Honor of Kings on your phone
-
- People play king of Glory
-
- King of Glory wins and loses by human manipulation
Case two: Put the elephant in the refrigerator
Process-oriented:
-
- Open the refrigerator door
-
- Put the elephant in
-
- Close the refrigerator door
Object-oriented:
-
- Create two objects: refrigerator and elephant
-
- New ways to open a fridge: Open the door (), act like an elephant (), close the door ()
-
- Refrigerator open: refrigerator. Open the door ()
-
- Refrigerator elephant: refrigerator. Pretend to be an elephant (Elephant)
-
- Refrigerator closes: refrigerator. Close the door ()
Case 3: Washing machineProcess-oriented:
-
- Turn on the washing machine
-
- Put the dirty clothes in
-
- Pour some laundry detergent
-
- Turn the tap and add water
-
- Start doing laundry
-
- Turn off the washing machine when you’re done
Object-oriented:
-
- Create two objects: people and washing machines
-
- Add ways to people: operate the washing machine, put out dirty clothes, turn on the tap, add laundry detergent
-
- Add to your washing machine: Wash clothes
-
- People turn on the washing machine: people. Turn on the washing machine ()
-
- People put dirty clothes: people. Put dirty clothes ()
-
- People with laundry detergent: people. Add laundry detergent (laundry detergent)
-
- People turn on the tap: people. Turn on the tap ()
-
- Washing machine Washing clothes: washing machine. Washing clothes ()
1.1 Process-oriented
From the above examples, we know that process orientation is to divide one thing into several steps to do, emphasizing the process of doing things.
For example, if you want to learn dragon eighteen palms, you need to learn the first type, and then learn the second type…… Finally, learn the 18th formula, each formula and the correlation between each formula is very strong, only after learning each formula in turn, to practice.
Advantages: Better performance than object oriented, because object oriented needs to create objects first, which consumes computer memory, so it is more suitable for small projects.
Disadvantages: The correlation between each step is too strong, the coupling degree is high, and it is not easy to expand.
1.2 Object-oriented
Through the above examples, we know that object orientation emphasizes the importance of objects, treats everything as objects and encapsulates everything related to them. Take the case of washing clothes in a washing machine:
People {open washing machine () put dirty clothes () add laundry liquid (laundry liquid)} refrigerator {wash clothes ()}Copy the code
The completion of a thing is divided into objects, give objects a certain function, and then by the division of labor between objects.
Advantages: Reusable code, easy to maintain and develop, extensible (for example, laundry detergent can be replaced when you don’t want to use laundry detergent), so more suitable for large projects.
Disadvantages: Lower than process-oriented performance
Conclusion:
- Process-oriented: Emphasizing process.
- Object orientation: Emphasis on objects, division of labor, and collaboration.
2. Classes and objects
Class: A class is an abstract concept that does not exist in the real world.
A class is essentially a thing with common features in the real world. The concept formed by extracting these common features is called “class”, such as human beings, animals, cars, birds and so on.
A class is a template that describes the “common characteristics” of all objects.
Object: Object is a concrete concept that exists in the real world. For example, Li Bai, Edison, Beckham are all objects, they all belong to human. An object is a real individual created from a class.
2.1 the abstract
The process of extracting common features from objects with the same features is called “abstraction”.
2.2 instantiation
An object is also known as an instance, and the process of creating an object from a class is called instantiation.
3. Class definition
We all know that classes have the same characteristics, and characteristics can be static or dynamic.
The static characteristic of birds is to have a pair of wings, and the dynamic characteristic is to fly. The static characteristic of dogs is a keen sense of smell, and the dynamic characteristic is to “bark”……
So, class = property + method
3.1 Java defines the syntax format of classes
[modifier]Class Class name {attribute + method} Note: The modifier can be omitted and will be explained later.Copy the code
Case one: Create a human in Java code
public class Person {
/ / name
private String name;
/ / age
private int age;
// Gender 0-female 1-male
private int sex;
/ / id card
private String idCard;
// How to eat
public void eat(a){
System.out.printf("Man must eat."); }}Copy the code
In the example above, attributes exist in the form of “variables.” Why is that?
Because attributes are static characteristics, attributes contain data, such as age 18, gender male, height 180. So in a Java program, data about attributes can only exist in variables.
Example 2: Create an animal class in Java code
public class Animal {
/ / weight
private int weight;
public void sleep(a){
System.out.println("Animals sleep."); }}Copy the code
Note: In Java, any type defined by class is a reference type; its type is the class name itself.
3.2 Instance Variables
Instance variables: Extract the common static characteristics of the object and store them in variables in the class, such as age, gender, height, etc.
The variables in the above class are instance variables, and since objects are also called instances, instance variables are object-level variables.
4. Object creation and use
4.1 Creating An Object
Now that we know how to define classes, how do we create objects?
That’s easy. New.
Syntax format:
Class name Variable name = new class name ();Copy the code
Our new object also needs to be received with a variable, for example:
Student student = new Student();
People people = new People();
Animal animal = new Animal();
Copy the code
4.2 Using Objects
Once the object is created, how do we use it? How do I get an object’s properties? How to access object methods?
Object. Property object. methods
public class Person {
/ / name
private String name;
/ / age
private int age;
// Gender 0-female 1-male
private int sex;
/ / id card
private String idCard;
// How to eat
public void eat(a){
System.out.printf("Man must eat.");
}
public static void main(String[] args) {
Person person1 = new Person();
System.out.println("Human Name No. 1:"+person1.name);
System.out.println("Human Age no. 1:"+person1.age);
System.out.println("Human Identity Card No. 1:"+person1.idCard);
person1.eat();
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
Person person2 = new Person();
System.out.println("Human Name no. 2:"+person2.name);
System.out.println("Human Age # 2:"+person2.age);
System.out.println("Human Identity Card No. 2:"+person2.idCard); person2.eat(); }}Copy the code
Running results:
We all know that a class can create many objects, but why is the age of the object created by humans 0? Why is id null?
This is because in Java, if we do not manually assign values to variables when creating objects, the system assigns values to instance variables by default. The default values are as follows:
The data type | The default value |
---|---|
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0 f |
double | 0.0 |
Reference types | null |
5. Draw a memory map
Why learn JVM memory maps?
Because the JVM memory map can deepen your understanding of how Java works.
When a Java VM runs Java programs, the memory it manages is divided into several areas. Each area has its own purpose, and its creation time and destruction time are different.
JVM memory is complex, and we’ll focus on three areas: stack, heap, and method areas.
Stack: Mainly holds method information, such as the main method.
Heap: Mainly holds object instances. You can think of it as “full of objects”.
Method area: this area is mainly used to store class information, static variables, constants, and compiled code by the compiler.
In the previous example, we created two objects of the Person class person1 and Person2.
Person1 and person2 actually store the memory addresses of objects in the heap: OX00001 and OX00002, so they point to two objects in the heap, respectively.
Therefore, when we access the instance variable of an object, we first find the object according to the memory address stored by the object variable, and then obtain the data stored by the instance variable of the object.
6. The null pointer is abnormal
Sometimes we get null-pointer exceptions, for example
public class Student {
/ / name
private String name;
public static void main(String[] args) {
Student student = null;
System.out.println("Student name:"+student.name); }}Copy the code
Running results:
Why is there a null pointer exception? You can see this by looking at the following memory diagram:
You create an empty object variable named student, which contains no memory address for any object. So when you access its instance variable, it can’t find an object in the heap, and it throws a null pointer exception.
7. Construction method
What’s the constructor? Through the literal meaning of “structure” vaguely feel that it is used for building things. But what?
Yeah, for making objects.
When you create a new object, you call the constructor to create the object and initialize its properties.
That is, the constructor is called before the object is created.
Note:
-
- When no constructor is provided in a class, a constructor with no arguments is provided by default.
-
- When a constructor is provided manually in a class, the system no longer provides a no-argument constructor by default.
7.1 Defining a constructor
Syntax format:
[modifier list] Constructor name (formal argument list){method body; }Copy the code
Note:
- Constructor names are the same as class names
- The constructor has no return value
- Multiple constructors can be defined in a class, and these constructors are actually method overloads
Such as:
public class Student {
/ / name
private String name = "A Ray of Thunder.";
public Student(a) {
System.out.println("I'm a constructor with no arguments.");
}
public static void main(String[] args) {
Student student = newStudent(); }}Copy the code
Running results:
7.2 Defining multiple constructors
public class Student {
/ / name
private String name;
public Student(a) {
System.out.println("I'm constructor 1.");
}
public Student(String name) {
System.out.println("I'm Constructor 2.");
}
public static void main(String[] args) {
Student student1 = new Student();
Student student2 = new Student("A Ray of Thunder."); }}Copy the code
Running results:
7.3 Initializing instance Variables using constructors
Such as:
public class Student {
/ / name
private String name;
public Student(a) {
System.out.println("I'm constructor 1.");
}
public Student(String name) {
System.out.println("I'm Constructor 2.");
this.name = name;
}
public static void main(String[] args) {
Student student = new Student("A Ray of Thunder.");
System.out.println("Name:"+student.name); }}Copy the code
Running results:
7.4 this
We used this keyword in the example above, so why this?
Let’s change the constructor in the above example:
public Student(String name) {
name = name;
}
Copy the code
Are you confused? Which is the argument I want to pass? Which is the instance variable of the object?
So this is used to distinguish between local variables and instance variables.
Note:
-
- This is a keyword and a reference that holds the memory address of the current object.
-
- This appears in the instance method to represent the current object.
-
- This cannot be used in static methods.
-
- This cannot be omitted when used to distinguish local variables from instance variables.
-
- This can appear in either a constructor or an instance method.
Such as:
public class Student {
/ / name
private String name;
public Student(String name) {
this.name = name;
}
public void printName(a){
System.out.println(this.name);
}
public static void main(String[] args) {
Student student = new Student("A Ray of Thunder."); student.printName(); }}Copy the code
Running results:
8. Encapsulation
Encapsulation is one of the three characteristics of object orientation, but what is encapsulation? Why encapsulate?
Let’s start with the following example:
public class Student {
String name;
String phone;
public Student(String name, String phone) {
this.name = name;
this.phone = phone; }}public class StudentTest {
public static void main(String[] args) {
Student student = new Student("A Thunderbolt."."18888888888");
System.out.println("Phone:"+student.phone);
student.phone = "110";
System.out.println("Phone:"+student.phone); }}Copy the code
Running results:
The Student class above is unwrapped, and the names and phone numbers are exposed, insecure, and easily tampered with.
Therefore, to ensure data security, it is necessary to encapsulate the class.
How does the Java language encapsulate?
-
- Attributes must be privatized, that is, decorated with the private keyword, and accessible only in this class.
-
- Provide set and GET methods externally. External programs can only set values by calling the object’s set method and get values by calling the object’s GET method.
-
- The modifiers for the set and GET methods must be public, that is, public and accessible in other classes.
Example after encapsulation:
public class Student {
private String name;
private String phone;
public Student(String name, String phone) {
this.name = name;
this.phone = phone;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone(a) {
return phone;
}
public void setPhone(String phone) {
this.phone = phone; }}Copy the code
Error found: Private property cannot be accessed
Get (); set ();
public class StudentTest {
public static void main(String[] args) {
Student student = new Student("A Thunderbolt."."18888888888");
System.out.println("Phone:"+student.getPhone());
student.setPhone("119");
System.out.println("Phone:"+student.getPhone()); }}Copy the code
Running results:
9. Three characteristics of object orientation
- encapsulation
- inheritance
- polymorphism
These three characteristics are interrelated, and any object-oriented programming language includes them. Inheritance and polymorphism will be discussed later.