1, Object oriented thought
1.1 overview of object-oriented thought
summary
Java language is an object-oriented programming language, and object-oriented thought is a programming thought. Under the guidance of object-oriented thought, we use java language to design and develop computer programs. The object here generally refers to all things in reality, and each thing has its own attributes and behavior. Object oriented idea is the design idea of abstracting the attribute characteristics and behavior characteristics of things with reference to real things in the process of computer design and describing them as computer events. It is different from the process oriented idea, which emphasizes that the function is realized by calling the behavior of the object, rather than operating and realizing it step by step.
give an example
wash clothes:
- Facing the process: take off the clothes – > find a basin – > put some washing powder – > add some water – > soak for 10 minutes – > knead – > wash the clothes – > wring dry – > dry
- Object oriented: take off clothes – > turn on the automatic washing machine – > throw clothes – > button – > hang them
difference:
- Process oriented: emphasizing steps
- Object oriented: emphasize the object. The object here is the washing machine.
characteristic
Object oriented thinking is an idea more in line with our thinking habits. It can simplify complex things and turn us from executor to commander.
Object oriented language contains three basic features, namely encapsulation, inheritance and polymorphism.
1.2 classes and objects
- Class: a collection of related properties and behaviors. It can be regarded as the template of a kind of things, and the attributes and behavior characteristics of things are used to describe this kind of things.
In reality, describe a class of things: - Attribute: is the state information of the thing
- Behavior: is what the thing can do
Example: kitten
Attributes: name, weight, age, color.
Behavior: walking, running and shouting
- Object: it is the concrete embodiment of a kind of things. An object is an instance of a class, which must have the properties and behavior of such things.
- In reality, an example of a kind of thing: a kitten.
Example: a kitten
Attributes: tom, 5kg, 2 years, yellow.
Behavior: sneaking around the wall, jumping and running, meowing
Relationship between class and object
- Class is the description of a class of things, which is abstract.
- An object is an instance of a class of things and is concrete.
- Class is the template of object, and object is the entity of class.
1.3 definition of class
Comparison of things and classes
A kind of thing in the real world
Attribute: state information of things. Behavior: what things can do.
The same is true for describing things with class in Java:
Member variable: attribute of corresponding thing member method: behavior of corresponding thing
Class definition format
public class ClassName{ //Member variable //Member method }
- Define class: defines the members of a class, including member variables and member methods.
- Member variables: almost the same as previously defined variables. It's just that the location has changed, in the class, outside the method.
- Member method: almost the same as the previously defined method. Just remove static.
Example of class definition format:
public class Student{ //Member variable String name;//full name int age;//Age //Member method //Learning methods public void study(){ System.out.println("study hard and make progress every day"); } //How to eat public void eat(){ System.out.println("Learn to eat when you are hungry"); } }
1.4 use of objects
Use format of object
Create object:
Class name object name = new class name ();
Using objects to access members in a class;
Object name. Member variable;
Object name. Member method ();
Example of object format:
public class Test01_Student{ public static void main(String[] args){ //Create object format: class name object name = new class name (); Student s = new Student(); System.out.println("s:"+s);//cn.itcast.Student@100363 //Direct output of member variable values System.out.println("full name:"+s.name);//null System.out.println("Age:"+s.age);//0 System.out.println("-------------"); //Assign values to member variables s.name = "Zhao Liying"; s.age = 18; //Output the value of the member variable again System.out.println("full name:"+s.name);//Zhao Liying System.out.println("Age:"+s.age);//18 System.out.println("-------------"); //Call member method s.study();//"Study hard and make progress every day" s.eat();//"Learn to eat when you're hungry" } }
Default values for member variables
1.5 class and object exercises
Define mobile phone class:
public class Phone{ //Member variable String brand;//brand int price;//Price String color;//colour //Member method //phone public void call(String name){ System.out.println("to"+name+"phone"); } //send message public void sendMessage(){ System.out.println("Mass texting"); } }
Define test class:
public class Test02Phone{ public static void main(String[] args){ //create object Phone p = new Phone(); //Output member variable value System.out.println("Brand:"+p.brand);//null System.out.println("Price:"+p.price);//0 System.out.println("Color:"+p.color);//null System.out.println("--------------"); //Assign values to member variables p.brand = "hammer"; p.price = 2999; p.color = "brown"; //Output the member variable value again System.out.println("Brand:"+p.brand);//hammer System.out.println("Price:"+p.price);//2999 System.out.println("Color:"+p.color);//brown System.out.println("--------------"); //Call member method p.call("Zixia"); p.sendMessage(); } }
1.6 object memory diagram
An object that calls a method memory graph
From the above figure, we can understand that the method running in the stack memory follows the principle of "first in first out". The variable p points to the space in the heap memory, looks for the method information and executes the method.
However, there are still problems here. When creating multiple objects, if a method information is saved inside each object, it will be a waste of memory, because the method information of all objects is the same. How to solve this problem? See the following illustration.
Memory graph of two objects calling the same method
When an object calls a method, it searches for the method information in the class according to the method tag (address value) in the object. In this way, even if there are multiple objects, only one copy of the method information is saved to save memory space.
A reference passed as a parameter to the memory map in the method
The reference type is used as a parameter, and the address value is passed.
1.7 differences between member variables and local variables
Variables have different names according to different definition positions, as shown in the following figure:
- Different positions in the class [ key ]
- Member variable: in class, outside method
- Local variable: in method or on method declaration (formal parameter)
- Different scope of action [ key ]
- Member variables: in classes
- Local variables: in method
- Different initialization values [ key points ]
- Member variables: have default values
- Local variable: there is no default value. It must be defined first, assigned, and used last
- Different locations in memory [understand]
- Member variables: heap memory
- Local variables: stack memory
- Different life cycles [understand]
- Member variable: exists with the creation of the object and disappears with the disappearance of the object
- Local variable: exists with the call of the object and disappears with the completion of the call of the object
2, Encapsulation
2.1 package overview
summary
Object oriented programming language is a simulation of the objective world. In the objective world, member variables are hidden in the object, and the outside world can't edit and modify them directly.
Encapsulation can be regarded as a protective barrier to prevent the code and data of this class from being accessed by other classes at will. To access the data of this class, it must be in a specified way. Appropriate encapsulation can make the code easier to understand and maintain, and also strengthen the security of the code.
principle
Hide the property. If you need to access a property, provide public methods to access it.
2.2 steps of packaging
1.use private Keyword to modify member variables 2.Provide a corresponding pair of member variables to be accessed getXxx Methods setXxx method.
2.3 encapsulated operation - private keyword
Meaning of private
1.private is a permission modifier, representing the minimum permission.
2. Member variables and member methods can be modified.
3. Member variables and member methods modified by private can only be accessed in this class.
Use format of private
private Data type variable name;
1. Modify the member variable with private. The code is as follows:
private class Student{ private String name; private int age; }
2. Provide getXxx method / setXxx method to access member variables. The code is as follows:
public class Student{ private String name; private int age; public void setName(String n){ name = n; } public String getName(){ return name; } public void setAge(int a){ age = a; } public int getAge(){ return age; } }
2.4 package optimization 1 – this keyword
We found that the name of the formal parameter in the / setXxx method does not meet the requirement of visibility. If the modification is consistent with the name of the member variable, is it visibility? The code is as follows:
public class Student{ private String name; private int age; public void setName(String name){ name = name; } public void setAge(int age){ age = age; } }
After modification and testing, we found a new problem, and the assignment of member variables failed. In other words, after modifying the image variable name of setXxx(), the method does not assign a value to the member variable! This is because the image variable name is the same as the member variable name, resulting in the member variable name being hidden, and the variable name in the method cannot access the member variable, so the assignment is invalid. Therefore, we can only use this keyword to solve the problem of duplicate names.
The meaning of this
this represents the reference (address value) of the current object of the class, that is, the reference of the object itself.
Remember: this in the method represents the object to which the method is called. That is, this represents who is calling.
this uses the format
this.Member variable name;
Use the variable in this modification method to solve the problem that the member variable is hidden. The code is as follows:
public class Student{ private String name; private int age; public void setName(String name){ //name = name; this.name = name; } public String getName(){ return name; } public void setAge(int age){ //age = age this.age = age; } public int getAge(){ return age; } }
Tip: when there is only one variable name in the method, the default is to use this modifier, which can be omitted.
2.5 package optimization 2 - construction method
When an object is created, the constructor is used to initialize the object and assign an initial value to the member variable of the object.
Tip: whether you customize the construction method or not, all classes have construction methods, because Java automatically provides a parameterless construction method. Once you define the construction method, the default parameterless construction method automatically provided by Java will become invalid.
Definition format of construction method
Modifier constructor name(parameter list){ //Method body }
The method name is the same as the class name of the constructor. It doesn't have a return value, so it doesn't need a return value type, or even void. After using the construction method, the code is as follows:
public class Student{ private String name; private int age; //Nonparametric construction method public Student(){} //Parametric construction method public Student(String name,int age){ this.name=name; this.age=age; } }
matters needing attention
1. If you do not provide a construction method, the system will give a parameterless construction method.
2. If you provide a construction method, the system will no longer provide a parameterless construction method.
3. The construction method can be overloaded, and parameters can be defined or not.
2.6 Standard Code - JavaBean
JavaBean is a standard specification for classes written in the Java language. Classes that conform to JavaBean are required to be concrete and public, have parameterless construction methods, and provide set and get methods for operating member variables.
public class ClassName{ //Member variable //Construction method //Nonparametric construction method [required] //Parameter construction method [recommended] //Member method //getXxx() //setXxx() }
Write classes that conform to JavaBean specifications. Take student classes as an example. The standard code is as follows:
public class Student{ //Member variable private String name; private int age; //Construction method public Student(){} public Student(String name,int age){ this.name = name; this.age = age; } //Member method public void setName(String name){ this.name = name; } public String getName(){ return name; } public void setAge(int age){ this.age= age; } public int getAge(){ return age; } }
Test class, code as follows:
public class TestStudent{ public static void main(String[] args){ //Use of parameterless construction Student s = new Student(); s.setName("Liuyan"); s.setAge(18); System.out.println(s.getName()+"---"+s.getAge()); //Use of parametric construction Student s2 = new Student("Zhao Liying",18); System.out.println(s2.getName()+"---"+s2.getAge()); } }