catalogue
2, Preliminary cognition of class and object
3, Classes and instantiation of classes
1. Field / attribute / member variable
1. private implementation encapsulation
1, Write in front
If you are interested in Java, you can pay attention to me as a small blogger. If you trust me, I will also improve the quality of my blog. It is best to teach at the nanny level to ensure that even if you are Xiaobai, you can learn and understand my blog. Of course, you should at least understand the most basic programming language knowledge. If you think this blog is good, please praise, comment and collect. No more nonsense. Let's learn.
2, Preliminary cognition of class and object
C language is process oriented, focuses on the process, analyzes the steps to solve the problem, and gradually solves the problem through function call.
JAVA is based on object-oriented and focuses on objects. It divides one 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 focuses on objects, that is, the subjects involved in the process. It is to connect each function realization 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 and behavior of the refrigerator. The refrigerator is an object, so as long as the functions of the refrigerator are operated, they should be defined in the refrigerator.
[object oriented concept]
1. Object oriented is a way of thinking and an idea. For example: concepts and examples. Theory and practice. Name and reality, etc.
2. Class is the general name of a class of objects. An object is an instance of this kind of materialization.
3. The benefits of object orientation: make complex things simple, just face an object.
[object oriented design]
Object oriented design holds an important experience: who owns data and who provides external methods to operate these data (private)! (the passive party is the owner of the data, and the active party is the executor)
During development: find objects, build objects, use objects, and maintain the relationship between objects.
Process oriented
object-oriented
3, Classes and instantiation of classes
1. Class
Class is a general term for a class of objects. An object is an instance of this kind of materialization.
Simple example: the model we use to make moon cakes is a class, and we can make moon cakes through this model. In this example, the class is the model and the moon cake is the object, so the moon cake is an entity. A model can instantiate countless objects.
In general: a class is equivalent to a template, and an object is a sample generated by the template. A class can produce countless objects.
Declaring a class is to create a new data type, and the class is a reference type in Java. Java uses the keyword class to declare the class. Let's look at the following simple declaration of a class.
Basic grammar
// Create class class <class_name>{ field;//Member properties method;//Member method } // Instantiate object <class_name> <Object name> = new <class_name>();
Class is the keyword defining the class, ClassName is the name of the class, and {} is the body of the class.
The elements in the class are called member attributes. The functions in the class are called member methods.
Example:
class Person { public int age;//Member property instance variable public String name; public String sex; public void eat() {//Member method System.out.println("having dinner!"); } public void sleep() { System.out.println("sleep!"); } }
2. Class instantiation
The process of creating objects with class types is called class instantiation
Class instantiation the process of creating objects with class types is called class instantiation
1. A class is just a model that defines which members a class has.
2. A class can instantiate multiple objects. The instantiated objects occupy the actual physical space and store class member variables.
3. Make an analogy. Class instantiation of objects is like building a house using architectural design drawings in reality. Class is like design drawings. It only designs what is needed, but there is no physical building. Similarly, class is only a design. The instantiated objects can actually store data and occupy physical space.
class Person { public int age;//Member property instance variable public String name; public String sex; public void eat() {//Member method System.out.println("having dinner!"); } public void sleep() { System.out.println("sleep!"); } } class Main{ public static void main(String[] args) { Person person = new Person();//Instantiate objects through new person.eat();//Member method calls need to be called by reference to the object person.sleep(); //Generate object instantiation object Person person2 = new Person(); Person person3 = new Person(); } }
matters needing attention
The new keyword is used to create an instance of an object
Use. To access properties and methods in an object
You can create multiple instances of the same class
class Person { //Ordinary member variables belong to objects private String name; private int age=19; //Static member variable - > class variable public static int count;//0 }
4, Member of class
1. Field / attribute / member variable
In the class, but the variables defined outside the method. Such variables are called "field" or "attribute" or "member variable" (all three names can be used, and generally they will not be strictly distinguished)
Used to describe what data a class contains
class Person { public String name; // field public int age; } class Test { public static void main(String[] args) { Person person = new Person(); System.out.println(person.name); System.out.println(person.age); } }
Use. To access the fields of an object
Access includes both read and write
For the field of an object, if the initial value is not explicitly set, a default initial value will be set
Default value rule
For various numeric types, the default value is 0
For boolean types, the default value is false
For reference types (String, Array, and custom classes), the default value is null
Know null
Null is a "null reference" in Java, which means that no object is referenced. It is similar to a null pointer in C language. If NULL is operated on, an exception will be thrown
class Person { public String name; public int age; } class Test { public static void main(String[] args) { Person person = new Person(); System.out.println(person.name.length()); // Get string length } }
Field local initialization
Many times, we don't want to use the default value for the field, but we need to explicitly set the initial value. It can be written as follows:
class Person { public String name = "Zhang San"; public int age = 18; } class Test { public static void main(String[] args) { Person person = new Person(); System.out.println(person.name); System.out.println(person.age); } }
2. Method
Used to describe the behavior of an object
class Person { public int age = 18; public String name = "Zhang San"; public void show() { System.out.println("My name is" + name + ", this year" + age + "year"); } } class Test { public static void main(String[] args) { Person person = new Person(); person.show(); } }
There is also a special method called construction method, which will be automatically called when instantiating an object. The method name is the same as the class name and is used for object initialization. Although we have been able to initialize properties locally, some more complex initialization logic may be required, Then you can use the construction method.
3. static keyword
1. Modification attribute
2. Modification method
3. Code block
4. Decoration class
a) Modifier attribute
Java static attributes are related to classes and not specific instances. In other words, different instances of the same class share the same static attribute
class TestDemo{ public int a; public static int count; } class Main{ public static void main(String[] args) { TestDemo t1 = new TestDemo(); t1.a++; TestDemo.count++; System.out.println(t1.a); System.out.println(TestDemo.count); System.out.println("============"); TestDemo t2 = new TestDemo(); t2.a++; TestDemo.count++; System.out.println(t2.a); System.out.println(TestDemo.count); } }
count is modified by static and shared by all classes. And it does not belong to an object. The access method is: class name. Attribute.
b) Modification method
If you apply the static keyword to any method, this method is called a static method.
Static methods belong to classes, not objects that belong to classes.
Static methods can be called directly without creating an instance of the class.
Static methods can access static data members and change the values of static data members.
class TestDemo{ public int a; public static int count; public static void change() { count = 100; //a = 10; error non static data members cannot be accessed } } class Main{ public static void main(String[] args) { TestDemo.change();//Can be called without creating an instance object System.out.println(TestDemo.count); } }
Note 1: static methods have nothing to do with instances, but are related to classes. Therefore, this leads to two situations:
Static methods cannot directly use non static data members or call non static methods (both non static data members and methods are instance related)
This and super keywords cannot be used in a static context (this is the reference of the current instance, super is the reference of the parent instance of the current instance, and is also related to the current instance)
Note 2:
Static is added to all the methods we have written for simplicity. But in fact, whether a method needs static or not depends on the situation. The main method is a static method
4. Summary
class Person { public int age;//Instance variables are stored in objects public String name;//Instance variable public String sex;//Instance variable public static int count;//Class variables are also called static variables. They have been generated during compilation. They belong to the class itself and have only one copy. Store in method area public final int SIZE = 10;//What is modified by final is called a constant, which also belongs to an object. It is modified by final and cannot be changed later public static final int COUNT = 99;//Static constants belong to the class itself. Only one is modified by final and cannot be changed later //Instance member function public void eat() { int a = 10;//local variable System.out.println("eat()!"); } //Instance member function public void sleep() { System.out.println("sleep()!"); } //Static member function public static void staticTest(){ //Non static members cannot be accessed //sex = "man"; error System.out.println("StaticTest()"); } } class Main{ public static void main(String[] args) { //Generate object instantiation object Person person = new Person();//person is a reference to the object System.out.println(person.age);//The default value is 0 System.out.println(person.name);//The default value is null //System.out.println(person.count);// There will be a warning! //Correct access method: System.out.println(Person.count); System.out.println(Person.COUNT); Person.staticTest(); //Summary: all methods or properties modified by static do not depend on objects. person.eat(); person.sleep(); } }
5, Encapsulation
What is encapsulation?
>The beginning is to discuss a problem: the essence of software development is the management of program complexity. If the complexity of a software code is too high, it can not continue to maintain. How to manage complexity? Encapsulation is the most basic method
When we write code, we often involve two roles: class implementer and class caller
The essence of encapsulation is that the caller of a class does not have to know much about how the class implementer implements the class, as long as he knows how to use the class
This reduces the learning and use cost of class users, thus reducing the complexity
1. private implementation encapsulation
The two keywords private/ public represent "access control"
Member variables or member methods modified by public can be directly used by class callers
The member variable or member method modified by private cannot be used by the caller of the class
In other words, the user of a class does not need to know or pay attention to the private members of a class, so that the class caller can use the class at a lower cost
Use public directly
class Person { public String name = "Zhang San"; public int age = 18; } class Test { public static void main(String[] args) { Person person = new Person(); System.out.println("My name is" + person.name + ", this year" + person.age + "year"); } }
This kind of code makes the user of the class (the code of the main method) have to understand the internal implementation of the Person class before they can use this class. The learning cost is high. Once the implementer of the class modifies the code (for example, changing the name to myName), the user of the class needs to modify his own code on a large scale, and the maintenance cost is high
class Person { private String name = "Zhang San"; private int age = 18; public void show() { System.out.println("My name is" + name + ", this year" + age + "year"); } } class Test { public static void main(String[] args) { Person person = new Person(); person.show(); } }
At this time, the field has been decorated with private. The caller of the class (in the main method) cannot use it directly. Instead, it needs to use the show method. At this time, the user of the class does not need to know the implementation details of the Person class
At the same time, if the implementer of the class modifies the name of the field, the caller of the class does not need to make any modification (the caller of the class cannot access fields such as name and age at all)
matters needing attention
Private can not only modify fields, but also modify methods. Generally, we will set fields as private attributes, but whether methods need to be set to public depends on the specific situation. Generally, we want a class to provide only "necessary" public methods, rather than setting all methods to public.
2. getter and setter methods
When we use private to decorate a field, we can't use this field directly
Code example
class Person { private String name = "Zhang San"; private int age = 18; public void show() { System.out.println("My name is" + name + ", this year" + age + "year"); } } class Test { public static void main(String[] args) { Person person = new Person(); person.age = 20; person.show(); } }
Code example
class Person { private String name;//Instance member variable private int age; public void setName(String name){ //name = name;// You can't write that this.name = name;//this reference represents the object that calls the method } public String getName(){ return name; } public void show(){ System.out.println("name: "+name+" age: "+age); } public static void main(String[] args) { Person person = new Person(); person.setName("caocao"); String name = person.getName(); System.out.println(name); person.show(); } }
matters needing attention
getName is the getter method, which means to get the value of this member
setName is the setter method, which means to set the value of this member
When the formal parameter name of the set method is the same as the name of the member attribute in the class, if this is not used, it is equivalent to self assignment. This represents the reference of the current instance
Not all fields must provide setter / getter methods, but which method to provide should be determined according to the actual situation. In IDEA, you can use alt + insert (or alt + F12) to quickly generate setter / getter methods
In VSCode, you can use the right mouse button menu - > source code operation to automatically generate setter / getter methods
6, Construction method
1. Basic grammar
Constructor is a special method. When instantiating a new object with the keyword new, it will be called automatically to complete the initialization operation
new execution process
Allocate memory space for objects
Call the constructor of the object
rule of grammar
1. The method name must be the same as the class name
2. The constructor has no return value type declaration
3. There must be at least one construction method in each class (if there is no clear definition, the system will automatically generate a parameterless construction)
matters needing attention
If no constructor is provided in the class, the compiler generates a constructor without parameters by default
If a constructor is defined in a class, the default parameterless constructor will no longer be generated
The construction method supports overloading. The rules are consistent with the overloading of ordinary methods
Code example
class Person { private String name;//Instance member variable private int age; private String sex; //Default constructor construction object public Person() { this.name = "caocao"; this.age = 10; this.sex = "male"; } //Constructor with 3 arguments public Person(String name,int age,String sex) { this.name = name; this.age = age; this.sex = sex; } public void show(){ System.out.println("name: "+name+" age: "+age+" sex: "+sex); } } class Main{ public static void main(String[] args) { Person p1 = new Person();//Call the constructor without parameters. If the program does not provide it, it will call the constructor without parameters p1.show(); Person p2 = new Person("zhangfei",80,"male");//Call the constructor with 3 parameters p2.show(); } }
2. this keyword
This indicates the current object reference (note that it is not the current object). You can use this to access the fields and methods of the object
class Person { private String name;//Instance member variable private int age; private String sex; //Default constructor construction object public Person() { //this calls the constructor this("bit", 12, "man");//It must be displayed on the first line } //The relationship between these two constructors is overloaded. public Person(String name,int age,String sex) { this.name = name; this.age = age; this.sex = sex; } public void show() { System.out.println("name: "+name+" age: "+age+" sex: "+sex); } } class Main { public static void main(String[] args) { Person person = new Person();//Calling a constructor without parameters person.show(); } }
We will find that inside the constructor, we can use the this keyword. The constructor is used to construct the object. Before the object is constructed, we use this. Does this still represent the current object? Of course not. This represents the reference of the current object.
7, Recognize code blocks
1. What is a code block
Fields are initialized in the following ways:
1. Local initialization
2. Initialize using the construction method
3. Initialize with code block
2. Common code block
class Main{ public static void main(String[] args) { { //Directly use {} definition, common method block int x = 10 ; System.out.println("x1 = " +x); } int x = 100 ; System.out.println("x2 = " +x); } }
3. Construct code block
class Person{ private String name;//Instance member variable private int age; private String sex; public Person() { System.out.println("I am Person init()!"); } //Instance code block { this.name = "bit"; this.age = 12; this.sex = "man"; System.out.println("I am instance init()!"); } public void show(){ System.out.println("name: "+name+" age: "+age+" sex: "+sex); } } class Main { public static void main(String[] args) { Person p1 = new Person(); p1.show(); } }
4. Static code block
class Person{ private String name;//Instance member variable private int age; private String sex; private static int count = 0;//Static member variables are shared by classes in the data method area public Person(){ System.out.println("I am Person init()!"); } //Instance code block { this.name = "bit"; this.age = 12; this.sex = "man"; System.out.println("I am instance init()!"); } //Static code block static { count = 10;//Only static data members can be accessed System.out.println("I am static init()!"); } public void show(){ System.out.println("name: "+name+" age: "+age+" sex: "+sex); } } class Main { public static void main(String[] args) { Person p1 = new Person(); Person p2 = new Person();//Will static code blocks still be executed? } }
matters needing attention
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 block) is executed, and then the constructor is executed.
8, Supplementary notes
1. toString method
class Person { private String name; private int age; public Person(String name,int age) { this.age = age; this.name = name; } public void show() { System.out.println("name:"+name+" " + "age:"+age); } } class Main { public static void main(String[] args) { Person person = new Person("caocao",19); person.show(); //We found that the hash value of an address is printed here. The reason: the toString method of Object is called System.out.println(person); } }
You can use methods like toString to automatically convert objects to strings
class Person { private String name; private int age; public Person(String name,int age) { this.age = age; this.name = name; } public void show() { System.out.println("name:"+name+" " + "age:"+age); } //Override the toString method of Object @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } } class Main { public static void main(String[] args) { Person person = new Person("caocao",19); person.show(); System.out.println(person); } }
matters needing attention:
The toString method will be called automatically at println
The operation of converting an object into a string is called serialization
ToString is the method provided by the Object class. The Person class created by us inherits from the Object class by default. We can override toString method to implement our own version of conversion string method. (we will focus on the concepts of inheritance and rewriting later.)
@Override is called "Annotation" in Java. Here @ override means that the toString method implemented below overrides the method of the parent class. The following courses will introduce annotation in detail
2. Anonymous object
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 Person { private String name; private int age; public Person(String name,int age) { this.age = age; this.name = name; } public void show() { System.out.println("name:"+name+" " + "age:"+age); } } class Main { public static void main(String[] args) { new Person("caocao",19).show();//Calling methods through anonymous objects } }
9, Summary of key contents
A class can produce countless objects. A class is a template and an object is a concrete instance.
The attributes defined in class can be roughly divided into several categories: class attributes and object attributes. The data attributes modified by static are called class attributes, and the methods modified by static are called class methods. The feature is that they do not depend on objects. We can call their attributes or methods only through the class name.
Static code block takes precedence over instance code block, and instance code block takes precedence over constructor.
this keyword represents the reference of the current object. Is not the current object.