⭐ ♪ previous words ⭐ ️
This article introduces you to Java classes and objects. I believe you have heard of object-oriented programming. Java is an object-oriented programming language. Different from C language, C language is a process oriented programming language. We can understand the difference between object-oriented and process-oriented. Object-oriented refers to a thing, which is nominal. Process oriented refers to doing things, which is verbal. For example, if you want to put an item into the refrigerator, process oriented is to open the ice box door - > put it in the refrigerator - > close the refrigerator; Object oriented is goods - > refrigerator. Classes and objects themselves are very abstract concepts, which need more understanding and practice. Let's start the text to take you to understand classes and objects in Java.
📒 Blog home page: Blog home page without flower smell
🎉 Welcome to pay attention 🔎 give the thumbs-up 👍 Collection ⭐ Leave a message 📝
📌 This article is original by Huawen, CSDN first!
📆 Starting time: 🌴 November 3, 2021 🌴
✉️ Persistence and hard work will surely bring poetry and distance!
💭 Reference books: 📚 Java core technology Volume 1, 📚 Java core technology Volume 2, 📚 Java programming ideas
💬 Refer to the online programming website: 🌐 Niuke network🌐Force buckle
🙏 The author's level is very limited. If you find an error, you must inform the author in time! Thank you, thank you!
The blogger's code cloud gitee, usually the program code written by the blogger is in it.
A class is a template or blueprint for constructing objects. We can think of a class as a cookie cutter
The process of constructing objects from classes is called creating instance s of classes
Instantiate a class. The instantiated class is an object.
C language is process oriented, focusing on the process, analyzing the steps to solve the problem, and gradually solving the problem through function calls. JAVA is based on object-oriented, focusing on objects. It divides a thing into different objects and completes it by the interaction between objects. Process oriented focuses on the process, and the behavior involved in the whole process is function. Object oriented It focuses on the object, that is, the subject involved in the process. It connects the functions through logic. Process oriented: 1. Open the refrigerator. 2. Put the elephant in. 3. Close the refrigerator. Object oriented: opening, storing and closing the refrigerator are the operation of the refrigerator and the behavior of the refrigerator. The refrigerator is an object, so as long as you operate the refrigerator Functions should be defined in the refrigerator.
The concept of class and object is very abstract. Let's understand class and object by introducing the application of class and object.
🔮 2. Class and class instantiation🎃 2.1 class creation
🎁 Customize the format of a class:
class ClassName { //Members: 1. Variables (fields / attributes) 2. Methods }
(1) The class name is named in the form of large hump
(2) A. java file can only have one class decorated with public
(3) Members in a class can be variables (fields / properties), methods, static variables and static methods.
For example:
class Student { public String name; public String sex; public int age; public String id; public void setName(String str){ name = str; } }
🎃 2.2 instantiation of class
The class we define can be understood as an architectural drawing (blueprint). The process of building a house according to the contents of this drawing is called class instantiation. The instantiated "house" is an object.
Of course, a design drawing can instantiate multiple buildings with the same properties. In other words, a class can instantiate multiple objects.
The keyword used to instantiate a class in Java is new. I believe you are no stranger to this keyword, because this keyword new is used in previous input and array definition.
class name change amount name = n e w class name ( structure make letter number ginseng number ) ; Class name \ variable name \ = \ new \ class name (constructor parameter); Class name Variable name = new Class name (constructor parameter);
Let's ignore this constructor parameter first. This parameter can be absent.
For example, we define such a class:
class Student { public String name; public String sex; public int age; public String id; public String major; public void getName() { System.out.println(name); } public void getMajor() { System.out.println(major); } }
Then the instantiation process of this class is:
public class ClassCreat { public static void main(String[] args) { Student stu = new Student();//Instantiate object stu.name = "weijianhuawen";//Use. To access the instantiated object stu stu.sex = "man"; stu.major = "computer"; stu.getMajor();//Similarly, the method of the object is accessed stu.getName(); } }
The variable stu defined by the Student class is a reference variable, and its value is the address of the instantiated object.
🎃 3.1 member variables
Variables defined outside methods in a class are called member variables of a class. Member variables are also called fields or properties.
class Variable { public int a public double pi; public String str; }
Variables defined outside the methods in the class as above are member variables. If we need to use this class, we need to instantiate an object with new before accessing the members inside. Through multiple objects instantiated by the class, each object is independent. Modify the value of one object, and the value of the other object will not change. Finally, the class The member variable in can initialize its own value or not, which is different from the local variable defined in the method. However, generally, it does not initialize its own value. If the member variable value is not initialized, there will be a default value.
public class ClassCreat { public static void main(String[] args) { Variable var = new Variable(); System.out.println(var.a); System.out.println(var.pi); System.out.println(var.str); var.pi = 3.14; var.a = 12; System.out.println(var.a); System.out.println(var.pi); System.out.println("---------------------"); Variable var2 = new Variable(); System.out.println(var2.a); System.out.println(var2.pi); } }
🎃 3.2 method
You can define methods in addition to member variables in a class. For example, the main method is defined in a class.
class Menthod { public double a; public double b; public double add(double x, double y) { return x + y; } public double sub(double x, double y) { return x - y; } }
We have defined a class with two member variables and member methods. If you need to use this class, you need to instantiate it into an object before accessing the variables or methods in the object.
public class ClassCreat { public static void main(String[] args) { Menthod men = new Menthod(); men.a = 3.14; men.b = 2.88; double sum = men.add(men.a, men.b); double sub = men.sub(men.a, men.b); System.out.printf("Hewei%.2f\n Difference is%.2f\n", sum, sub); } }
🎃 3.3 static variables and static methods
The member variables and member methods defined above outside the methods in the class belong to objects and are stored in the heap. Static variables or static methods are stored in the method area, and classes are also stored in the method area, so static variables or methods are also called class variables and class methods. Static variables and static methods belong to classes, so there is no need to implement the class Instantiation can be used. Of course, because it belongs to a class, if you change the value of a static variable in an object, the static value will be the modified value when accessing the static variable in other objects.
class StaticMember { public static int x; public static int add(int a, int b) { return a + b; } }
In the class defined above, a is a member variable, b is a static member variable, and there is a static method add. As mentioned above, using a static variable or method does not need to instantiate an object with a class (of course, you can instantiate an object and access it according to the object, which is no problem). A must instantiate an object before it can be used.
public class ClassCreat { public static void main(String[] args) { int a = 12; int sum = StaticMember.add(a, StaticMember.x); System.out.println(sum); System.out.println("------------"); StaticMember sm1 = new StaticMember(); sm1.x = 14; sum = sm1.add(a, sm1.x); System.out.println(sum); System.out.println("------------"); StaticMember sm2 = new StaticMember(); sum = sm2.add(a, sm2.x); System.out.println(sum); } }🔮 4. Encapsulation of class
🎃 4.1 privite implementation package
When we define a variable or method in a class, we use the public keyword to modify it. A variable or method modified with this keyword means that the variable or method is public and can be used in other and current classes. However, if we use the privilege keyword to modify a variable or method, it means that the variable or method is private and can only be accessed and used by its class, The variable or method cannot be accessed or called in other classes, which also reflects the security of Java.
Look at the following code:
class PriviteMember { private int add(int a, int b) { return a + b; } } public class ClassCreat { public static void main(String[] args) { PriviteMember pm = new PriviteMember(); int x = 10; int y = 12; System.out.println(pm.add(x, y)); } }
Because we private the add method in the PriviteMember class, and then instance the object in another class and use add, we find that the compiler reports an error!
If the method calling add (mian method in the sample program) is in the same class as add, execute the program again:
public class ClassCreat { private int add(int a, int b) { return a + b; } public static void main(String[] args) { ClassCreat pm = new ClassCreat(); int x = 10; int y = 12; System.out.println(pm.add(x, y)); } }
We found that this method works properly:
🎃 4.2 getter and setter methods
The variable or method modified by the keyword privite can only be used in the same class. If we want to modify or call the privite variable or method in another class, can we implement it? In fact, it is possible, but indirect. That is, we define a public modified method in the class of the variable or method modified by privite to access and modify the members modified by privite.
We can write such a class:
class PriviteMember { private int m; private double n; private int add(int a, int b) { return a + b; } public int getterInt() { return m; //Get m } public double getterDouble() { return n;//Get n } public void setterInt(int x) { m = x;//Set m } public void setterDouble(double y) { n = y;//Set n } public int getAdd(int x, int y) { return add(x, y);//Call private method add } }
We call other public variables or methods in other classes, which can indirectly access and modify private members.
public class ClassCreat { public static void main(String[] args) { PriviteMember pm = new PriviteMember(); pm.setterInt(12);//Assign value to m System.out.println(pm.getterInt());//Gets the value of m pm.setterDouble(3.14);//Assign value to n System.out.println(pm.getterDouble());//Gets the value of n int a = 14; int b = 12; System.out.println(pm.getAdd(a, b));//Call private method add indirectly } }
In fact, in the compiler idea, getter and setter methods can be automatically generated to set and obtain the value of private variables or the return value of private methods in a class.
In the idea compiler, right-click in the code area, find Generate, click in and select Getter or Setter to automatically help you Generate, set and obtain the value of private member variables.
Select Getter or Setter as needed, and then select the variable to access. Press and hold ctrl to select multiple variables.
this keyword refers to the reference in the current object, which can be used to access the member variables and methods of the current object.
🎃 5.1 new execution process
👻 5.1.1 new instantiation object process
The process of instantiating an object using the keyword new is actually divided into two steps:
- Allocate memory space for objects
- Call the constructor (if there is no constructor in the class, a constructor without parameters will be generated automatically)
👻 5.1.2 construction method
Constructor is a special method. It will be called automatically when instantiating a new object with the keyword new. Therefore, the constructor is defined in the class. It has the following characteristics:
- The method name must be the same as the class name.
- No return value.
- There is at least one constructor in each class. If it is not defined in the class, a constructor without parameters will be automatically generated.
- The construction method supports overloading, and the rules are consistent with those of ordinary methods.
- If a constructor with parameters is defined in the class, the default parameterless constructor will no longer be generated.
🎃 5.2 this keyword
Keyword this when using Setter to generate a function, it is found that variables in the automatically generated function are modified by this keyword, which represents references in the current object and can be used to access member variables and methods of the current object.
❗ Attention! This refers to the reference of the current object, not the current object. We can use this in the constructor, but when calling the construction method, the object has not been instantiated, but the memory has been allocated, indicating that the object has not been defined, but the reference has been generated. Because the memory allocation is completed, the address will be given, The quotation came out naturally. So this represents a reference to the current object, not the current object.
The following code can prove that this can be used in the construction method:
class ConstructionMethod { public int a; private int b; public ConstructionMethod() { System.out.println("This is a construction method without parameters!"); } public ConstructionMethod(int x) { this.b = x; System.out.println("This is a construction method with parameters! You can give member variables b Assignment! After assignment b = " + this.b); } public ConstructionMethod(int x, int y) { this.a = this.add(x, y); System.out.println("This is a construction method with two parameters! You can calculate the sum of two integers! The sum of these two numbers is:" + a); } private int add(int m, int n) { return m + n; } }
public class ClassCreat { public static void main(String[] args) { ConstructionMethod cm1 = new ConstructionMethod(); System.out.println("------------"); ConstructionMethod cm2 = new ConstructionMethod(12); System.out.println("------------"); ConstructionMethod cm3 = new ConstructionMethod(18, 2); } }🔮 6. Code block
🎃 6.1 common code block
A normal code block is a code block defined by curly braces in a method, for example:
public class ClassCreat { public static void main(String[] args) { { int a = 12; int b = 48; String name = "weijianhuawen"; } } }
🎃 6.2 building blocks
The construction code block is the code block defined outside the method in the class, also known as the instance code block. It is generally used to initialize member variables (I think it's unnecessary), for example:
class CodeBlock { private int c; private int d; public int sum; //Construct code block or instance code block { this.c = 10; this.d = 12; sum = this.add(c, d); } public int add(int x, int y) { return x + y; } }
❗ Note: Construction (instance) code block takes precedence over constructor execution.
🎃 6.3 static code block
The construction code block decorated with static is called static code block, which is generally used to initialize the attributes of static member variables. It is stored with the class in the method area.
class CodeBlock { public static int a; public static String name; //Static code block static { a = 18; name = "No smell of flowers"; } }
❗ ⅶ note:
- No matter how many objects are generated, the static code block will be executed only once and first.
- After the static code block is executed, the instance code block (construction code block) is executed, and then the constructor is executed.
🎃 7.1 output object data
What will be output when we print a reference to a class? Let's try:
class Student { public String name; public String sex; public int age; public String id; public String major; public void getName() { System.out.println(name); } public void getMajor() { System.out.println(major); } } public class ClassCreat { public static void main(String[] args) { Student sc = new Student(); sc.name = "weijianhuawen"; sc.sex = "man"; sc.age = 1; sc.id = "5201314"; sc.major = "computer"; System.out.println(sc); } }
Why not output the address? Because Java has strong security, it processes the address, uses the toString method to return a string, and the printed data is the string. As for why toString method is used, let's trace back to the true face of println method:
Press and hold ctrl and click to enter the println method:
Through traceability, we know that printing a reference will output a string such as the class name @ the hash value of the reference.
Let's try to write such a method ourselves. The return value of the method name is the same as that of the toString method.
If I write it like this and put it in the Student class:
public String toString() { return "No smell of flowers"; }
Let's run this program again:
class Student { public String name; public String sex; public int age; public String id; public String major; public String toString() { return "No smell of flowers"; } public void getName() { System.out.println(name); } public void getMajor() { System.out.println(major); } } public class ClassCreat { public static void main(String[] args) { Student sc = new Student(); sc.name = "weijianhuawen"; sc.sex = "man"; sc.age = 1; sc.id = "5201314"; sc.major = "computer"; System.out.println(sc); } }
Get the string returned by toString I wrote. This is actually a rewriting of the method. If the method in the subclass is the same as the method name return value parameters and the number of parameters in the parent class, it constitutes a rewriting of the method, and the subclass's methods will be executed first (this content will be described in detail in the subsequent blog on inheritance, which will be understood here first). The class Student I wrote is a subclass. The original toString method is in the Object class. The Object class is the parent class, so the toString method I wrote will be executed first.
In the idea compiler, the toString method can be automatically generated, and the data of member variables in a class can be selectively output.
Similar to auto generate Getter and Setter methods:
Automatically generated code:
Run the program again:
class Student { public String name; public String sex; public int age; public String id; public String major; @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + ", id='" + id + '\'' + ", major='" + major + '\'' + '}'; } public void getName() { System.out.println(name); } public void getMajor() { System.out.println(major); } } public class ClassCreat { public static void main(String[] args) { Student sc = new Student(); sc.name = "weijianhuawen"; sc.sex = "man"; sc.age = 1; sc.id = "5201314"; sc.major = "computer"; System.out.println(sc); } }
🎃 7.2 anonymous objects
The so-called anonymous object is called directly instead of using the reference variable of a class. Then the generated object is one-time and can only be accessed once, because you can't find it after accessing it once.
- Objects that are not referenced are called anonymous objects
- Anonymous objects can only be used when creating objects
- If an object is used only once and does not need to be used later, consider using anonymous objects
class AnonymousObject { public int a; public AnonymousObject() { this.a = 188; } } public class ClassCreat { public static void main(String[] args) { System.out.println(new AnonymousObject().a); } }The old fellow who felt that the article was well written, praised the comments and paid attention to a wave. Thank you!