JAVA classes and objects

Keywords: Java jvm

1. Preliminary cognition of class and object


[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)

Note: during development: find objects, build objects, use objects, and maintain the relationship between objects.
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

2. Class and class instantiation

Type 2.1

Class is a general term for a class of objects. An object is an instance of this kind of materialization

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.

// 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.

2.2 instantiation of class

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

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

3. Members of the class

3.1 field / attribute / member variable

The member variables (without static) in the class are stored on the heap

Used to describe what data is contained in a class

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);
   }
}
// results of enforcement
null
0

matters needing attention:

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


Know null

Indicates that the reference does not point to any memory space. If the reference is still used to access memory, the operation will be abnormal.

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
   }
}
// results of enforcement
Exception in thread "main" java.lang.NullPointerException
        at Test.main(Test.java:9)

3.2 method

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();
   }
}
// results of enforcement
 My name is Zhang San, He is 18 years old

The show method here indicates that the Person object has a "show yourself" behavior
Such a show method is associated with the person instance. If other instances are created, the behavior of show will change

3.3 static keyword

Note: static has nothing to do with the object and is called directly through the class name

3.3.1 modification attributes

Static attribute: represents a class attribute. All objects of the class share the same property and are called directly through the class name

The reference data type saves the address of the object (saved on the user interface)
All the objects from new () are on the heap.
Static properties are saved in the JVM method area

3.3.2 modification method

Static method: it is called directly through the class name without generating the object of the class

3.3.3 modifier code block

3.3.4 decoration

4. Packaging

Reflected in ease of use and encapsulation

4.1 private implementation encapsulation

When a property is modified by private, the property is only visible inside the class and cannot be used outside the class.

4.2 getter and setter methods

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(); 
 } 
} 
// Compilation error
Test.java:13: error: age Can be in Person Medium access private 
 person.age = 20; 
 ^ 
1 Errors

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){ 
 //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(); 
} 
// Operation results
caocao 
name: caocao age: 0

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
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

5. Construction method

5.1 basic grammar

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

new execution process
1. Allocate memory space for objects
2. Call the construction method of the object

a. If no constructor is provided in the class, the compiler generates a constructor without parameters by default
b. If constructor is defined in class, JVM no longer generates default parameterless constructor
c. Constructor supports overloading (consistent with normal constructor)
d. Constructor supports calling each other

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

Overloading of construction methods

1. Arrange in ascending order according to the parameters (number) of the construction method
2. Use this(); Must be placed on the first line of the construct overload

5.3 this keyword

1. Decorated attribute: it means to find attributes directly from this class
2. Modification method: it means to call the method in this class
3.this means (this is who calls this method through which object)

6. Code block

Normal code block: a code block defined in a method
Construction code block: a code block defined in a class and generated directly with {} without any modifiers
When an object is generated, it is implemented once with an object·
Static block: defined in a class and decorated with static (generated when the class is loaded) static code blocks will be executed only once and first no matter how many objects are generated
Synchronous code block

7. Supplementary notes

toString method

When you define a class, you can use a method such as toString to automatically convert the object into a string

Code example:

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("caocao",19); 
 person.show(); 
 System.out.println(person); 
 } 
} 
// results of enforcement
name: caocao age: 19 
Person{name='caocao', age=19}

be careful:

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. 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
Shortcut key of toString method for IDEA to quickly generate Object: alt+f12(insert)

Anonymous object

Posted by choppsta on Sun, 28 Nov 2021 17:30:46 -0800