Understanding of classes and objects in JAVA

1, Object oriented
Object oriented (OOP) programs are composed of objects, and each object contains specific functional parts exposed to users. Many objects in the program come from the standard library, and some are customized. Whether you construct the object yourself or buy it from the outside completely depends on the budget and time of the development project. However, fundamentally speaking, as long as the object can meet the requirements, there is no need to care about the specific implementation process of its function. In OOP, there is no need to care about the specific implementation of the object, as long as it can meet the needs of users.
Object oriented focuses on objects, that is, the subjects involved in the process. It is to connect each function realization through logic. In short, object-oriented is a way to use code (class) to describe things in the objective world. A class mainly contains the attributes and behavior of a thing.
[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.

2, Classes and instantiation of classes
Type 2.1
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 take a look at simply declaring a class:

class Person{

//Field attribute member variables are defined inside the class and outside the method
//Member variables are divided into ordinary member variables and static member variables
public String name;
public int age;
//Member method
//Member methods are divided into ordinary member methods and static member methods
public void eat(){
    System.out.println(name +"I am eating");
}
public void sleep(){
    System.out.println(name +"be sleeping");
}

}

Class is the keyword defining the class, Person 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.

2.2 instantiation of class
The process of creating objects with class types is called class instantiation.

A class is just a model that defines which members a class has
A class can instantiate multiple objects. The instantiated objects occupy the actual physical space and store class member variables
For example. 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
For example:

class Person{

public String name;
public int age;//Member property instance variable
//Member method
//Member methods are divided into ordinary member methods and static member methods
public void eat(){ //Member method
    System.out.println(name +"I am eating");
}
public void sleep(){ //Member method
    System.out.println(name +"be sleeping");
}

}
public class Test01 {

public static void main(String[] args) {
    Person person = new Person();//Instantiate objects through new
    person.name = "zhang";
    person.age = 10;
    System.out.println(person.name); //The access of member variables needs to be accessed through the reference of objects
    person.eat();//Calling a method through a reference to an object
    person.sleep();
    //Generate object instantiation object
    Person person2 = new Person();//A class can instantiate multiple objects
    Person person3 = new Person()
}

Summary:

The new keyword is used to create an instance of an object
Use. To access properties and methods in an object
The same class can instantiate multiple objects
2.3 members of class
Class members can include the following: fields, methods, code blocks, internal classes, interfaces, and so on.
Let's first look at fields (member variables):

2.3.1 field / attribute / member variable
In a class, but a variable defined outside the method. Such a variable is called "field" or "attribute" or "member variable".
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
In many cases, we don't want to use the default value for the field, but we need to explicitly set the initial value, which can be written as follows:

class Person {

public String name = "Zhang San";
public int age = 18;

}

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

public static void main2(String[] args) {

    Person person = null;//Represents that this reference does not point to any object
    Person person1 = new Person();
    Person person3 = person1;//Represents that the reference of person3 points to the object pointed to by the reference of person1

    person1 = new Person(); //A reference cannot point to multiple objects at the same time
    person1 = new Person();
    person1 = new Person();
}

2.3.2 method
Method is used to describe the behavior of an object.
For example, the eat method and sleep method in example 2.2 indicate that the person object has a "show yourself" behavior. Such eat method and sleep method are associated with the person instance. If other instances are created, the behavior of eat method and sleep method will change. java training

2.3.3 static keyword
All methods or properties modified by static do not depend on the object

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;

}
public 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);
}

}

Output results:

1 1

1 2

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.
For static member variables, they are accessed directly through the class name: class name. Static member properties / methods.
public static void staticFunc() {
//Ordinary methods cannot be called inside static methods. Static methods do not depend on objects

    System.out.println("static::func()");
}
public void eat(){
    System.out.println(name + "I am eating");
}
public void print(){
    staticFunc();

//Static methods can be called inside ordinary methods, but static variables cannot be defined

    System.out.println("full name:" + name + ",Age:" + age);
}

Static methods are independent of instances, but 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 a reference to the current instance, and super is a reference to the parent instance of the current instance, which is also related to the current instance)
c. Code block
Code blocks defined using static. It is generally used to initialize static member attributes, which will be explained in detail later in the code block.

d. Modifier class
3, Encapsulation
3.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
A 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

Private can not only modify fields, but also modify methods. Usually, 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

3.2 getter and setter methods
When we use private to modify a field, we cannot directly use this field. At this time, if we need to obtain or modify this private property, we need to use getter / setter methods

class Person{

private   String name;
private   int age;

 public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

}

[note]:

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 should be provided according to the actual situation
4, Construction method
Constructor is a special method. When instantiating a new object with the keyword new, it will be automatically called to complete the initialization operation. The constructor has no return value.
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 it is not clearly defined, the system will automatically generate a parameterless construction

[note]:

If no constructor is provided in the class, the compiler will generate a constructor without parameters by default. That is, a class will have at least one constructor
If there are other constructors in the current class, the compiler will not help us generate constructors without parameters
Overloads can be formed between construction methods, and the rules are consistent with those of ordinary methods
Overload: the method name is the same, the parameter list is different, and the return value is not required.
class Person{

private   String name;
private   int age;

public Person(){

    System.out.println("Construction method without parameters");
}
 public  Person(String name,int age){
    this.name = name;
      System.out.println("Construction method with 1 parameter");

}

public  Person(String name,int age){
    this.name = name;
    this.age = age;
    System.out.println("Construction method with 2 Parameters");

}
public void show(){

System.out.println("name: "+name+" age: "+age);
}

}
public class Main{
public static void main(String[] args) {

Person p1 = new Person();//Call the constructor without parameters. If the program does not provide parameters, it will call the constructor without parameters
p1.show();
Person p2 = new Person("zhangfei");//Call constructor with 1 argument
p2.show();
Person p3 = new Person("zhangfei",80);//Call the constructor with 2 parameters
p3.show();
}

}

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

1. this.data calls the properties of the current object
Example:

public void setName(String name){
    this.name = name;//this represents a reference to the current object
}
public String getName(){
    return name;
}

2. this.func() calls the method of the current object
Example:

public void eat(){

    System.out.println(name + "I am eating");
}
public void print(){
    this.eat();
    staticFunc();
    //Static methods can be called inside ordinary methods, but static variables cannot be defined
    System.out.println("full name:" + name + ",Age:" + age);
}

3. this() calls other construction methods of the current object and stores them in the constructor!
Example:

public Person(){

   this("name",12);//When calling the constructor with 2 parameters, this must be placed on the first line
    System.out.println("Construction method without parameters");
}
public  Person(String name,int age){
    this.name = name;
    this.age = age;
    System.out.println("Construction method with 2 Parameters");
}

Output results:

Construction method with 2 Parameters
Construction method without parameters
name 12

5, Code block
A piece of code defined using {}
According to the location and keywords defined by the code block, it can be divided into the following four types:
1. Common code block
2. Structural block
3. Static block
4. Synchronization code block

class Person{

//Common member variable, belonging to object
private   String name;
private   int age;

//Static member variables cannot be defined in methods
public static int count = 10;//Static member variables - > class variables are placed in the method area

{
    this.age = 90;
    System.out.println("Instance code block");
}
static {
    //Essentially, initialize something static
    count = 99;  //If it is static, it has something to do with the order of definition
    System.out.println("Static code block");
}

public static void main5(String[] args) {

    Person person1 = new Person();//Static code block
    System.out.println("==============");
    Person person2 = new Person();  //Instance code blocks static code blocks are executed only once
}
 public static void main6(String[] args) {
    System.out.println(Person.count);//Static code blocks can be executed without instantiating objects, and only once
}

Static code blocks and instance code blocks are executed when the class is loaded.
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.
Static code blocks can be executed without instantiating objects.

Anonymous object
Anonymity simply means an object without a name
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);
}

}
public class Main {

public static void main(String[] args) {
new Person("caocao",19).show();//Calling methods through anonymous objects
}

}
//Execution results
name: caocao age: 19

toString method
In the above four, we use the show method. In fact, we can use the toString method:

@Override / / override

public String toString() {
    return "Person{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';

[note]:

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 ourselves inherits from the Object class by default. You can override toString method to implement our own version of conversion string method
@Override is called "Annotation" in Java. Here @ override means that the toString method implemented below is a method that overrides the parent class.

Keywords: Java Class

Added by dougmcc1 on Mon, 01 Nov 2021 04:33:20 +0200