Classes and objects in Java

Keywords: Java Back-end

catalogue

1, Preliminary cognition of class and object

2, Class and class instantiation

1. Basic syntax of class

2. Class instantiation

3. Member of class

3.1. Member variables / attributes

3.2 understanding

3.3 method

3, Construction method

4, Keywords

1. this keyword

(1) Call the member variable through the this keyword

(2) Calling member methods with the this keyword

(3) this keyword calls the constructor

2. static keyword

(1) Modifier attribute

(2) Modification method

5, Class encapsulation

1. How to realize encapsulation

2.getter and setter methods

6, Code block

1. Common code block

2. Construct code block

3. Static code block

7, toString method

  8, Anonymous object

9, Try ox knife at the end

1, Preliminary cognition of class and object

C language is Process oriented of follow Yes process , analyze the steps to solve the problem, and gradually solve the problem through function call.
JAVA is Based on object oriented of follow Yes Object, a thing is divided into different objects, which is completed 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.
The characteristics of object-oriented can be summarized as follows: Packaging Inheritance Polymorphism.
Later, we will introduce encapsulation and the use of inheritance. We will talk about polymorphism in detail later.

2, Class and class instantiation

Class is a general term for a class of objects. An object is an instance of this kind of materialization.
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.
To declare a class is to create a new data type Java Belong to reference type , Java Use keywords class To declare a class.
Let's simply declare a class:

1. Basic syntax of class

class < class_name > {  
    field ; // Member properties
    method ; // Member method
}
// Instantiate object
< class_name > < Object name > = new < class_name > ();
class To define the keyword of the class, class_name Is the name of the class, {} Is the body of the class.
The elements in a class are called: member attributes; The functions in the class are called member methods.
The following is a complete class:
class Person {
    public int age;//Member properties
    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 types is called class instantiation.
one   Class is just a Model The same thing specifies which members of the class.

2. A class can instantiate multiple objects. Only the instantiated objects occupy the actual physical space and store class member variables.

(the instantiation of objects by classes is like building a house using architectural design drawings in reality. Classes are like design drawings, only designing what needs to be done.)
West, but there is no physical building. Similarly, the class is only a design. Only the instantiated object can actually store data and occupy physical space)

Let's instantiate an object through the class of the previous 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!");  
   }
}
public 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();
        Person person2 = new Person();
        Person person3 = new Person();
 }
}

//Operation results
 having dinner!
sleep!

3. Member of class

3.1. Member variables / attributes

In class , However, variables defined outside the method . Such variables are called  " attribute " or " Member variable ''.
class Person {
    public String name;   //Member variable
    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);
   }
}



// results of enforcement
null
0

Note: if the initial value is not explicitly set for the field of an object, a default initial value will be set.

  1. For various number types, the default value is 0 (float and double are 0.0 by default)
  2. For boolean types, the default value is false
  3. For char type, the default is null character, '\ u0000'
  4. For reference types (String, Array, and custom classes), the default value is null

3.2 understanding

null stay Java Zhongwei " Null reference ", Indicates that no object is referenced . be similar to C Null pointers in languages . If yes null A null pointer exception is thrown when an operation is performed( NullPointerException )

3.3 method

Methods are often used to describe the behavior of an object. For example:
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();
   }
}


// results of enforcement
 My name is Zhang San, He is 18 years old
There is also a special method called Construction method  . The method that will be automatically called when instantiating the object, The method name is the same as the class name, Used for object initialization.

3, Construction method

Basic syntax:

Construction method is a special method. When a new object is instantiated with the keyword new, it will be automatically called to complete the initialization operation.

be careful:
1. The method name must be the same as the class name.
2. Constructor has no return value type declaration.
3. There must be at least one construction method in each class (if there is no explicit definition, the system will automatically generate a parameterless construction method. This default construction method not only has no parameters, but also has no code in the method weight, that is, it does nothing. If we have defined a construction method, the system will not automatically generate a default construction method)
4. A return statement cannot be used in a method to return a value, but a return statement can be written separately as the end of the method.
5. The construction method supports overloading, and the rules are consistent with the overloading of ordinary methods. (the previous chapter describes the overloading of ordinary methods in detail)
Take an example and feel:
class Person { 
 
 private String name;//Member variable
 private int age; 
 private String sex; 
 //Default parameterless constructor
 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); 
 } 
} 

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

// results of enforcement
name: caocao age: 10 sex: male
name: zhangfei age: 80 sex: male

4, Keywords

1. this keyword

This refers to the current object and is used to access other members of the object in the method. Next, let's talk about three common uses of this keyword in the program.

(1) Call the member variable through the this keyword

        Resolve conflicts with local variable names.
Take an example:
class Person{
   int age;                      //Member variable age
   public Person(int age){       //Local variable age
      this.age=age;              //Assign the value of the local variable age to the member variable age
  } 
}

As in the above example, if "age" is used in the construction method, local variables are accessed, and if "this.age" is used, member variables are accessed.

(2) Calling member methods with the this keyword

As follows:

class Person{
 public void openMouth(){
     ....
  }
 public void speak(){
     this.openMouth();
  }
}

Through the above example, we used the this keyword to call the openMouth() method. It should be noted that the this keyword here can be omitted without writing, and the effect is the same. Therefore, we won't repeat it, but it means that it can be called in this way.

(3) this keyword calls the constructor

The construction method is automatically called by the Java virtual machine when instantiating the object. In the program, other construction methods can be called in the form of "this [parameter 1, parameter 2,...]" in one construction method.

class Person{
   public Person(){
       System.out.println("The parameterless constructor was called...");
  }
   public Person(int age){
       this();
       System.out.println("The constructor with parameters was called...");
 }
}

public class testdemo{
    public static void main(String[] args){
      Person p=new Person(18);
  }
}

//Operation results
 The parameterless constructor was called...
The constructor with parameters was called...

Analyze the above code: when instantiating the Person object, the constructor with parameters is called, and the constructor without parameters is called through this() in the constructor with parameters. Therefore, the running results show that both constructors have been called.

When using this to call the constructor of a class, you should pay attention to the following points:

1. this can only be used in constructor to call other constructor methods, not in other member methods.

2. In a construction method, the statement that uses this to call the construction method must be the first execution statement of the method and can only appear once.

2. static keyword

First, the static keyword can be used to——

1. Modifier attribute
2. Modification method
3. Code block
4. Modification class (internal class will be discussed later, and it is estimated that the next article )

(1) Modifier attribute

Java static attributes are related to classes, not specific instances. In other words, different instances of the same class can share the same static attribute.

When the attribute is modified by static, it is shared by all classes and does not belong to an object. The access method is: class name. Attribute.

class TestDemo{
    public int a;
    public static int count;  //Define static member variables
}

public class Main{   
 public static void main(String[] args) {
        TestDemo t1 = new TestDemo();
        t1.a++;
        TestDemo.count++;  //The class name. Attribute is used directly when calling
        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);
   }
}

//Operation results
1
1
============
1
2

be careful:

1. Static keyword can only be used to modify member variables, not local variables (that is, a variable cannot be declared as static in non static methods), otherwise an error will be reported during compilation!

Why? Because variables decorated with static can be accessed by instantiated objects of any class, and variables declared in methods are local. After the method is executed, it needs to be destroyed to free up space.

(2) Modification method

If applied on any method static Keyword, this method is called a static method.
be careful:
a. Static methods (class name. Static method name) can be called directly without creating an instance of the class.
b. Static methods can access static data members and change the values of static data members.
It's still a little abstract. Last example:
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
   }
}
public class Main{
public static void main(String[] args) {
        TestDemo.change();   //Can be called without creating an instance object
        System.out.println(TestDemo.count);   
   }
}

//Operation results
100

be careful:

Static methods have nothing to do with objects, but are related to classes. Therefore, two situations are caused:

1. Static methods cannot directly use non static data members or call non static methods (because non static data members and methods are instance related).

2,this  and   super  Two keywords cannot be used in a static context (this Is a reference to the current object ,super Is a reference to the parent object of the current object , both with Current object (related)
(3) Memory layout of data attributes:
For example, the following program code——
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);
   }
}

//Operation results
1
1
============
1
2

Its distribution in memory is as follows:

  As can be seen from the above figure:

Java has stack memory and heap memory. The stack memory is used to store basic type variables (local variables) and object reference variables (such as t1 and t2 in this example), and the heap memory is used to store objects (such as member variable a in this example) and arrays created by new.

However, the static variable (count in this example) has been generated during compilation and belongs to the class itself, and there is only one copy. It is stored in the method area.

5, Class encapsulation

1. How to realize encapsulation

Class encapsulation means that the state information of the object is hidden inside the object, and the external program is not allowed to directly access the internal information of the object, but to access the internal information through the methods provided by the class.

Its specific implementation process is to privatize the attributes in the class, that is, to modify them with the private keyword. If the outside world wants to access private properties, it needs to provide some common methods decorated with public.

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

// results of enforcement
 My name is Zhang San, He is 18 years old
  • At this point, the field has been decorated with private. The caller of class cannot use it directly, but needs to use the show method. At this point, the user of the class does not have to understand the implementation details of the Person class.
  • At the same time, if the implementer of the class modifies the name of the member variable, the caller of the class does not need to make any modification (because the caller of the class can't access variables such as name and age), so the code maintenance cost is greatly reduced.

2.getter and setter methods

When we use private to decorate a field, we can't use this field directly. At this time, if you need to get or modify the private property, you need to use the getter / setter method.  

class Person { 
 private String name;    //Instance member variable
 private int age; 
 
 public void setName(String name){ 
 this.name = name;
 } 

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


// Operation results
caocao 
name: caocao age: 0
Shortcut keys:
stay IDEA Can be used in alt + insert ( perhaps alt + F12) Fast generation setter / getter method.
stay VSCode You can use the right mouse button - > menu - > Automatically generated in source code operation setter / getter method.

6, Code block

use    { }   A piece of code defined .
According to the location and keywords defined by the code block, it can be divided into the following three types:
  • Common code block
  • Tectonic block
  • Static block

1. Common code block

Common code blocks are: code blocks defined in methods.

public class Main{ 
 public static void main(String[] args) { 
 { 
 int x = 10 ;     //Directly use {} definition, common method block
 System.out.println("x1 = " +x); 
 } 
 int x = 100 ; 
 System.out.println("x2 = " +x); 
 } 
} 


// results of enforcement
x1 = 10 
x2 = 100

2. Construct code block

Construction code block: a code block defined in a class ( No modifier ) . Also known as: Instance code block . Construction code blocks are generally used to initialize instance member variables.
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 (also known as construction code block)
 { 
 this.name = "Zhang San"; 
 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); 
 } 
 
} 
public class Main { 
 public static void main(String[] args) { 
 Person p1 = new Person(); 
 p1.show(); 
 } 
} 
// Operation results
I am instance init()! 
I am Person init()! 
name: Zhang San age: 12 sex: man

From the above example -- the instance code block takes precedence over the constructor.

3. Static code block

use static Defined code block. Generally used to initialize static member properties.
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 and stored in the method area

    public Person(){
        System.out.println("Execute constructor!");
    }

    //Instance code block
    {
        this.name = "Zhang San";
        this.age = 12;
        this.sex = "man";
        System.out.println("Execute instance code block!");
    }

    //Static code block
    static {
        count = 10;  //Only static data members can be accessed
        System.out.println("Execute static code block!");
    }

    public void show(){
        System.out.println("name: "+name+" age: "+age+" sex: "+sex);
    }

}
public class Main {
    public static void main(String[] args) {
        Person p1 = new Person();
        Person p2 = new Person();
        p2.show();
    }
}

//Operation results
 Execute static code block!
Execute instance code block!
Execute constructor!
Execute instance code block!
Execute constructor!
name: Zhang San age: 12 sex: man

From the above example, we can conclude that:

1. No matter how many objects are generated, static code blocks are executed only once and first.

2. If static, instance and constructor exist, the execution order is: static code block > instance code block > constructor.

7, toString method

Let's start with a sample code:

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) { 
 Person person = new Person("haha",19); 
 System.out.println(person); 
 } 
} 

// results of enforcement
Person@1c168e5

  We found that the hash value of an address is printed here. The reason: the toString method of Object is called. This method hashes the memory address of the Object and returns a hash value of type int.

In actual development, we usually hope that the toString () method returns not only the basic information of the object, but some more useful information. Therefore, we can rewrite the 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); 
 } 
 //Override the toString method of Object
 @Override 
 public String toString() { 
 return "Person{" + 
 "name='" + name + '\'' + 
 ", age=" + age + 
 '}'; 
 } 
} 
public class Main { 
 public static void main(String[] args) { 
 Person person = new Person("haha",19); 
 System.out.println(person); 
 } 
} 
// results of enforcement
Person{name='haha', age=19}
Summary:
1,toString The method will be in println Automatically called when.
2. The operation of converting an object into a string is called Serialization.
3,toString yes Object Class , We created it ourselves Person Class inherits from by default Object Class (an object class is provided in Java, which is the father of all classes, and each class inherits directly or indirectly from this class) So we Can override toString Method implements our own version of the conversion string method. ( Concepts like inheritance and rewriting , I'll go into more detail in the next article )
4,@Override stay Java Called in " annotation ", Here @Override Represents the following implementation toString Method is a method that overrides the parent class . Notes will be described in detail in the following courses.
5,IDEA Fast generation Object of toString Method shortcut: alt+f12(insert)
perhaps   Right click and select Generate "toString()" to select the member to be generated. (if you are not sure, please refer to the steps below.)
>> >>

 

  8, Anonymous object

Anonymity simply means that an object has no name (no reference). Anonymous objects can only be used when creating objects. If an object is used only once , It doesn't need to be used in the back , 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("Zhang San",19).show();   //Calling methods through anonymous objects
 } 
} 
// results of enforcement
name: Zhang San age: 19

9, Try ox knife at the end

After learning the above knowledge, let's end with a small topic ~ you can also knock on the code.

Title: realize the exchange of the values of two variables. Requirements: you need to exchange the values of arguments (don't fake exchange)

Think about it and watch it again

3

2

1

The answers are announced below——

class MyValue {
    public int val;
}
public class Main {
    public static void swap(MyValue myV1,MyValue myV2) {
        int tmp = myV1.val;
        myV1.val = myV2.val;
        myV2.val = tmp;
    }

    public static void main(String[] args) {
        MyValue myValue1 = new MyValue();
        myValue1.val = 10;

        MyValue myValue2 = new MyValue();
        myValue2.val = 20;

        swap(myValue1,myValue2);

        System.out.println("myValue1:"+myValue1.val+";" +"myValue2:"+myValue2.val);
    }
}

//Operation results
myValue1:20;myValue2:10

Some students may not understand it. It seems that this writing method has no change from the previous values. In fact, we pass references. It's better to draw a picture.

  This section is over. See you next section~

to be continue →

Welcome to discuss and exchange with each other. Welcome to catch insects!

 

Posted by raku on Thu, 11 Nov 2021 21:57:10 -0800