First knowledge of object-oriented
Classes and objects
What is an object?
Object is a very important concept in programming language and real world. The so-called "all things are objects" means that the objective things existing in reality are objects.
What is object oriented?
① Suppose we go to the zoo to see animals one day
② We describe the animal needs we want to see to the administrator.
- Fat
- lovely
③ After listening, the administrator took us to see panda banbu and black bear ton
The process of going to the zoo to see animals is actually an object-oriented process.
When we go to the zoo to see animals, when we say our needs, the animals are virtual; When the administrator leads us to see animals, the animals at this time are entities, which is the way to deal with problems in our life.
Relationship between class and object
- A class is a model (template) that determines the characteristics (properties) and behaviors (Methods) that an object will have
- An object is an instance representation of a class
- Class is the type of object
- Objects are specific types of data
Properties and methods
Attributes: various static characteristics of objects - "what does an object have"
Method: objects have various dynamic behaviors - "what can objects do"
Back to the example of visiting the zoo, the characteristics of animals are the attributes of objects; What animals can do is the method of objects
summary
- class
- Abstract concept
- Template
- object
- A concrete thing that actually exists
Create class
Implementation steps of object-oriented in java programming:
Create a pet cat class Cat.java to describe the attributes and behavior methods of the pet cat
package animal; /** * Pet cats * @author Zhao * */ public class Cat { //Member attributes: name, age, weight, variety String name;//name int month;//Age double weight;//weight String species;//varieties //Method: run and eat //Running method public void run() { System.out.println("Kitten, run!"); } //How to eat public void eat() { System.out.println("Kittens eat!"); } }
Instantiate object
Create a test class CatTest.java to instantiate the object and call the properties and methods of the object.
package object.start; /** * @author Ning * @date 2021/9/20 10:57 */ public class CatTest { public static void main(String[] args) { //Instantiate an object - > use the new keyword Cat one = new Cat(); //Properties of the calling object one.name = "tearful"; one.month = 2; one.weight = 1000; one.species = "british shorthair "; //Call the method of the object one.eat(); one.run(); //Output the property value of the object System.out.println("name:"+one.name); System.out.println("Age:"+one.month); System.out.println("weight:"+one.weight); System.out.println("varieties:"+one.species); } }
Note: if the object's properties are not initialized, the system will assign initial values to the object's properties by default.
The initial value of an integer is 0
The initial value of a floating-point type is 0.0
The initial value of the string is null
Single responsibility principle
We will find that the previously written code is placed in a class, including the main method; In object-oriented programming, the main method and the class encapsulating attributes and methods are separated, which is the single responsibility principle (single function principle)
Single responsibility principle
The so-called "single responsibility principle" means that there is and only one cause of change in a class.
Simply put, a class should preferably have only one function.
For example, the following hamsters are doing experiments:
If we want to observe the movement of hamsters, we just need to let them run; If you want it to run, but also let it run a distance and jump up, the hamster's heart is broken.
Therefore, in a class, if the class undertakes more functions, the degree of integration and coupling of this class will be higher, and the possibility of reuse will be lower.
What happens when there is more integration and coupling?
The higher the integration and coupling, it may lead to changes in other responsibilities in the same category, and then affect the operation of the whole program.
This is like the scene of crossing the road in our life. Many people like to play mobile phones while walking; Many people like to make phone calls while driving, so once an accident occurs, it is a very terrible thing.
new keyword
In object-oriented, we instantiate objects through the new keyword.
Instantiate object
The process of instantiating an object can be divided into two parts:
① Declaration object Cat one
② Instantiate object new Cat();
When declaring an object, if one in the memory space is null, it cannot access properties and methods.
Why can you access properties and methods after instantiating an object?
After instantiating an object, it will open up a space in the heap space of memory to complete the initialization of object information.
Note: declared objects and instantiated objects are in different spaces
Declare that the object is in stack space; The instantiated object is in heap space.
So how do stack space and heap space relate?
After instantiating an object, the memory address of the object in the heap space will be stored in the stack, so that the declared object points to the instantiated space.
If you instantiate an object with the new keyword, will the two objects send a conflict?
Let's modify the code of CatTest.java, and let's create a new object
package object.start; /** * @author Ning * @date 2021/9/20 10:57 */ public class CatTest { public static void main(String[] args) { //Instantiate an object - > use the new keyword Cat one = new Cat(); //Instantiate another object Cat two = new Cat(); //Properties of the calling object one.name = "tearful"; one.month = 2; one.weight = 1000; one.species = "british shorthair "; //Assign a value to the property of two two.name = "Fanfan"; two.month = 1; two.weight = 800; two.species = "Chinese garden cat"; //Output the property value of the object System.out.println("name:"+one.name); System.out.println("Age:"+one.month); System.out.println("weight:"+one.weight); System.out.println("varieties:"+one.species); System.out.println("------------------------------"); System.out.println("name:"+two.name); System.out.println("Age:"+two.month); System.out.println("weight:"+two.weight); System.out.println("varieties:"+two.species); } }
Operation results:
Name: Huahua
Age: 2
Weight: 1000.0
Breed: British short haired cat
Name: Fanfan
Age: 1
Weight: 800.0
Breed: Chinese garden cat
We find that two objects instantiated with the new keyword will not conflict.
Whenever we use the new keyword, we will open up a space in the heap space to store the address of the object. Although they are all cats, they point to different addresses. Even if their attribute values are exactly the same, they do not affect each other.
This is as like as two peas of two houses. Even if the interior of the house is exactly the same, the key to the house is two different keys.
Is new the only way to implement object instantiation?
Let's modify the CatTest.java code
package object.start; /** * @author Ning * @date 2021/9/20 10:57 */ public class CatTest { public static void main(String[] args) { //Instantiate an object - > use the new keyword Cat one = new Cat(); //Assign object one to object two Cat two = one; //Properties of the calling object one.name = "tearful"; one.month = 2; one.weight = 1000; one.species = "british shorthair "; //Assign a value to the property of two two.name = "Fanfan"; two.month = 1; two.weight = 800; two.species = "Chinese garden cat"; //Output the property value of the object System.out.println("name:"+one.name); System.out.println("Age:"+one.month); System.out.println("weight:"+one.weight); System.out.println("varieties:"+one.species); System.out.println("------------------------------"); System.out.println("name:"+two.name); System.out.println("Age:"+two.month); System.out.println("weight:"+two.weight); System.out.println("varieties:"+two.species); } }
Operation results:
Name: Fanfan
Age: 1
Weight: 800.0
Breed: Chinese garden cat
Name: Fanfan
Age: 1
Weight: 800.0
Breed: Chinese garden cat
We found that the attribute values of the object become the attribute values set by the object two.
In fact, the object one copies the memory address and puts it into the object two. At this time, both point to the same memory area. Therefore, whoever modifies the attribute will affect the other party.
It's like two people living in a house. Anyone can decorate the house.
Construction method
Constructors are also called constructors and constructors. You can complete the relevant settings of object initialization through construction methods.
Syntax of construction method
Access modifier constructor name (parameter list){
Initialization code block
}
Relevant rules of construction method
① Constructor and class names must be the same and have no return value
② Can only be used when an object is instantiated
③ When no construction method is specified, the system will provide a parameterless construction method by default
④ When there is a specified construction method, whether it is a parametric or nonparametric construction method, the nonparametric construction method will not be automatically added
⑤ There can be more than one constructor in a class
Nonparametric construction method
When we write the code in Cat.java file, we don't write a parameterless constructor. The system will automatically add a parameterless constructor to us. This time, we manually add a parameterless constructor to Cat.java
//Nonparametric construction method public Cat(){ System.out.println("Cat Parameter free construction method, which we added manually..."); }
Call the parameterless constructor we added manually in CatTest.java
package object.start; /** * @author Ning * @date 2021/9/20 10:57 */ public class CatTest { public static void main(String[] args) { //Instantiate an object - > use the new keyword Cat one = new Cat(); //The system initializes the object through the parameterless construction method } }
Operation results:
Cat's parameterless construction method, which we added manually...
Parametric construction method
We used to assign the initial value to the attribute of the object through the object name. Attribute name = attribute value. When there are too many attributes of the object, it will be troublesome to assign values one by one. Therefore, we can add a parameter construction method to the class to initialize the value of the attribute.
Adding parameter constructor in Cat.java
//Parametric construction method public Cat(String name, int month, double weight, String species) { name = name; month = month; weight = weight; species = species; }
Test in CatTest.java
package object.start; /** * @author Ning * @date 2021/9/20 10:57 */ public class CatTest { public static void main(String[] args) { //Instantiate an object - > use the new keyword //Initialize the property using a parameterized constructor Cat one = new Cat("tearful",2,1000,"british shorthair "); System.out.println("name:"+one.name); System.out.println("Age:"+one.month); System.out.println("weight:"+one.weight); System.out.println("varieties:"+one.species); } }
Operation results:
Name: null
Age: 0
Weight: 0.0
Variety: null
expand
We explicitly initialize the attribute value through the parameterized construction method, but why is it not assigned successfully?
We made a logical error, and a warning message appeared in our parameter constructor - The assignment to variable name has no effect. The variable is not working.
The reason is that when the parameter name in the parameter list has the same name as the member variable name, because there is no specific specification, whether the variable is a variable in the construction method or a member variable, the system will adopt the proximity principle, so the member variable will not be assigned a value.
There are two solutions:
① Modify the variable name Cat.java in the parameter list
//Parametric construction method public Cat(String newName, int newMonth, double newWeight, String newSpecies) { name = newName; month = newMonth; weight = newWeight; species = newSpecies; }
Results after CatTest.java is run:
Name: Huahua
Age: 2
Weight: 1000.0
Breed: British short haired cat
② Through this keyword
this keyword
This can refer to the current object. The current object refers to who calls this. This keyword can access both properties and methods.
Modify the parametric construction method of Cat.java through the this keyword
//Parametric construction method public Cat(String name, int month, double weight, String species) { this.name = name; this.month = month; this.weight = weight; this.species = species; }
CatTest.java running result:
Name: Huahua
Age: 2
Weight: 1000.0
Breed: British short haired cat