Java Classes and Objects

Keywords: Java Back-end

1. Preliminary Cognition of Classes and Objects

C language is process-oriented and focuses on the process, analyzing the steps to solve the problem, and gradually solving the problem through function calls.
JAVA is object-oriented and focuses on objects. It splits one thing into different objects and completes them through interaction between objects.
Process-oriented focuses on process, and the behavior involved in the process is function.
Object-oriented focuses on objects, that is, the subjects involved in the process of participation. Connecting a function through logic
Process-oriented: 1. Open the refrigerator 2. Put elephants in the refrigerator 3. Close the refrigerator Object-oriented: Open the refrigerator, store, close are all operations to the refrigerator, is the behavior of the refrigerator. The refrigerator is an object, so as long as you operate the functions that the refrigerator has, you have to define it in the refrigerator.

2. Instantiation of classes and classes

Class is the general name of a class of objects. An object is an example of this kind of materialization.
Simple example: We make a mooncake's module is a class, through which we can make mooncakes. In this example, the class is that module, and the mooncakes are that object, so the mooncakes are an entity. A module can instantiate an infinite number of objects.
Generally speaking, a class is equivalent to a template, and the object is a sample generated by the template. A class that can produce an infinite number of objects.
Declaring a class creates a new data type, and the class is a reference type in Java, which uses the keyword class to declare the class. Let's look at the following simple declaration of a class.

class Person {
    //Field-"Attribute-" Member Variable--> Inside Class, Outside Method is called Member Variable-> 1. Ordinary Member Variable 2. Static Member Variable
    public String name;
    public int age;

    //Method-"Behavior
    public void eat() {
        System.out.println(name + "I am eating");
    }

    public void sleep() {
        System.out.println(name + "Be sleeping");
    }
}

public class TestDemo {
    public static void main(String[] args) {
        Person person = new Person();//Instantiate Object
        person.age = 10;
        person.name = "bit";
        //Member variable access via object reference
        System.out.println(person.name);//Reference type member variable is not initialized to null
        System.out.println(person.age);//int member variable not initialized to 0
        person.eat();
        person.sleep();
        System.out.println("================");
        Person person1 = new Person();
        System.out.println(person1.name);
        System.out.println(person1.age);

    }


Class is the keyword that defines the class, Person is the name of the class, and {} is the body of the class.
Elements in a class are called member attributes. A function in a class is called a member method.

Matters needing attention
The new keyword is used to create an instance of an object.
Use.To access properties and methods in objects.
The same class can create pairs of instances.

3. Class members

3.1 Fields/Attributes/Member Variables

Members of a class can include fields, methods, code blocks, internal classes, interfaces, and so on.

class Person2 {//Fields, attributes, member variables
    public String name;//Full name
    public int age;//Age
}

public class TestDemo1 {
    public static void main(String[] args) {
        Person2 p1 = new Person2();
        System.out.println(p1.name);
        System.out.println(p1.age);
    }

}

Matters needing attention
Use.Access object fields.Access contains both read and write.
If no initial value is explicitly set for a field of an object, a default initial value is set

Default Value Rule

  1. For various numeric types, the default value is 0.
  2. For boolean types, the default is false.
  3. For reference types (String, Array, and custom classes), the default value is null

Know null

Null is a "null reference" in Java, meaning no object is referenced. It is similar to a null pointer in C. If null is used. An exception is thrown.

class Person2 {//Fields, attributes, member variables
    public String name;//Full name
    public int age;//Age
}

public class TestDemo1 {
    public static void main(String[] args) {
        Person2 p1 = new Person2();
        System.out.println(p1.name);
        System.out.println(p1.age);
        System.out.println(p1.name.length());
    }
}


Fields are initialized in place: this is not typically done.

class Person2 {//Fields, attributes, member variables
    public String name = "Hellen";//Full name
    public int age = 30;//Age
}

public class TestDemo1 {
    public static void main(String[] args) {
        Person2 p1 = new Person2();
        System.out.println(p1.name);
        System.out.println(p1.age);
    }
}

3.2 Method: Used to describe the behavior of an object.

class Person2 {//Fields, attributes, member variables
    public String name = "Hellen";//Full name
    public int age = 30;//Age


    public void introduce(){
        System.out.println("I am"+ name + ",This year"+age+"Age!");
    }
}


public class TestDemo1 {
    public static void main(String[] args) {
        Person2 p1 = new Person2();
        System.out.println(p1.name);
        System.out.println(p1.age);
        p1.introduce();

        Person2 p2=new Person2();
        p2.name="James";
        p2.age=22;
        p2.introduce();
    }
}


There is also a special method called the construction method.

3.3 static keyword

1. Modifying Attributes
2. Modification Methods
3. Code blocks (introduced in this courseware). 4. Modifier classes (covered later in Internal classes)

a) Modifying attributes, Java static attributes and class-related, independent of specific instances. In other words, different instances of the same class share the same static attribute.

class Person2 {//Fields, attributes, member variables
    public String name = "Hellen";//Full name
    public int age = 30;//Age
    public int a;
    public static int count;
    public void introduce(){
        System.out.println("I am"+ name + ",This year"+age+"Age!");
    }
}


public class TestDemo1 {
    public static void main(String[] args) {
        Person2 p1 = new Person2();
        p1.a++;
        Person2.count++;
        System.out.println(p1.a);
        System.out.println(Person2.count);
        
        System.out.println("=============");
        
        Person2 p2=new Person2();
        p2.a++;
        Person2.count++;
        System.out.println(p2.a);
        System.out.println(Person2.count);
    }
}


b) Modification method
If the static keyword is applied to any method, it is called a static method.

  1. Static methods belong to classes, not objects of classes.
  2. Static methods can be called directly without creating instances of classes.
  3. Static methods can access static data members and change their values, but static variables cannot be defined inside static methods
class Person2 {//Fields, attributes, member variables
    public String name = "Hellen";//Full name
    public int age = 30;//Age
    public int a;
    public static int count;
    public void introduce(){
        System.out.println("I am"+ name + ",This year"+age+"Age!");
    }

    public static void set(){
        count=100;
    }
}


public class TestDemo1 {
    public static void main(String[] args) {
        Person2.set();
        System.out.println(Person2.count);
    }
}


Total:
1. Static member variables cannot be defined in methods
2. You cannot call a normal method inside a static method because the static method does not depend on the object, while the normal method depends on the object 3. You can call a static method inside a normal method

Note 1:

  1. Static methods and instances are not related, but to classes. This leads to two scenarios:
  2. Static methods cannot directly use non-static data members or call non-static methods (both non-static data members and methods are instance related).
  3. The keywords this and super cannot be used in a static context (this is a reference to the current instance, super is a reference to the parent instance of the current instance, and is related to the current instance).
    Note 2
  4. The methods we've written are all static for simplicity, but in fact a method needs to be case-dependent, whether it's static or not.
  5. The main method is the static method.

4. Packaging

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 costs of the class user and reduces the complexity.

4.1 private Implementation Encapsulation

  1. Member variables or member methods modified by public can be used directly by the caller of the class.
  2. Member variables or member methods modified by private s cannot be used directly by the caller of a class.
class Person2 {//Fields, attributes, member variables
    private String name = "Hellen";//Full name
    private int age = 30;//Age
    public void introduce(){
        System.out.println("I am"+ name + ",This year"+age+"Age!");
    }
    public class TestDemo1 {
    public static void main(String[] args) {
        Person2 p1=new Person2();
        p1.introduce();
    }
}

  1. The field is now decorated with private s. The caller of the class (main method) cannot use it directly. Instead, the introduce method is needed. The user of the class does not have to know the implementation details of the Person class.
  2. Also, if the class implementer modifies the name of a field, the caller of the class does not need to make any changes (the caller of the class does not have access to fields such as name, age at all).

Matters needing attention
3. private not only modifies fields but also methods
4. Usually we will set the field as the private property, but whether the method needs to be public or not depends on the specific situation. Generally, we want a class to provide only the "necessary" public methods, not all methods to be public.

4.2 getter and setter methods

When we use private s to modify a field, we can't use it directly.

class Person2 {//Fields, attributes, member variables
    private String name = "Hellen";//Full name
    private int age = 30;//Age
    public void introduce(){
        System.out.println("I am"+ name + ",This year"+age+"Age!");
    }
    public class TestDemo1 {
    public static void main(String[] args) {
        Person2 p1=new Person2();
        p1.age=10;
        p1.introduce();
    }
}


If you need to get or modify this private property, you need to use the getter / setter method:

class Person2 {//Fields, attributes, member variables
    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;
    }
}


    public class TestDemo1 {
        public static void main(String[] args) {
            Person2 p1=new Person2();
            p1.setName("James");
            System.out.println(p1.getName());
            System.out.println("=============");
            p1.setAge(20);
            System.out.println(p1.getAge());

        }
    }


Matters needing attention

  1. getName is the getter method that gets the value of this member.
  2. setName is the setter method that sets the value of this member.
  3. If this is not used, it is equivalent to a self-assignment when the parameter name of the set method is the same as the name of the member property in the class. This represents a reference to the current instance.
  4. Not all fields have to provide setter / getter methods, but it's up to you to decide which one to provide.
  5. setter / getter methods can be quickly generated in IDEA using alt + insert (or alt + F12). setter / getter methods can be automatically generated in VSCode using the right mouse button menu - > source code operations.

5. Construction methods

5.1 Basic Grammar

Construction method: Method name is the same as class name, no return value
The role of construction methods

  1. Allocate memory for objects
  2. Call the appropriate object's construction method (more than one)

Be careful:
3. If no construction method is written, the compiler automatically generates a construction method with no parameters
4. If the current class has other constructors, the compiler will not generate constructors without parameters
5. Overloads can be formed between construction methods

class Person2 {//Fields, attributes, member variables
    private String name;
    private int age;
    private String sex;

    //Default constructor constructor object
    public Person2() {
        this.name = "caocao";
        this.age = 10;
        this.sex = "male";
    }

    //Constructor with 3 parameters
    public Person2(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;


    }

    @Override
    public String toString() {
        return "Person2{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}


public class TestDemo1 {
    public static void main(String[] args) {
        Person2 p1 = new Person2();
        System.out.println(p1.toString());

        System.out.println("================");
        Person2 p2 = new Person2("James", 34, "female");
        System.out.println(p2.toString());
    }
}

5.2 this keyword

Be careful:

  1. this keyword represents a reference to the current object
  2. this.data calls the properties of the current object
  3. this.fun() calls the method of the current object
  4. this() calls the other construction methods of the current object, which must be placed on the first line and can only be stored in the construction methods
class Person2 {//Fields, attributes, member variables
    private String name;
    private int age;
    private String sex;

    //Default constructor constructor object
    public Person2() {
        //this calls the constructor
        this("Hellen",22,"female");
    }

    //Constructor with 3 parameters
    public Person2(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;


    }

    @Override
    public String toString() {
        return "Person2{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}


public class TestDemo1 {
    public static void main(String[] args) {
        Person2 p1 = new Person2();//Call construction method without parameters
        System.out.println(p1.toString());
    }
}

We will find that inside the constructor, we can use this keyword, the constructor is used to construct the object, the object has not been constructed, we use this, does this still represent the current object? Of course not. This represents a reference to the current object.

6. Understanding Code Blocks

Fields are initialized in the following ways:

  1. In-place Initialization
  2. Initialize using a construction method
  3. Initialization using code blocks
    You've learned the first two before, and we'll move on to the third, initializing with code blocks.

6.1 What is a code block

A piece of code defined with {}.
Depending on where the code block is defined and the keyword, it can be divided into the following four types:

  1. Normal Code Block
  2. Constructor Block (Instance Code Block)
  3. Static block
  4. Synchronize Code Blocks (discussed in the Multithreaded section later)

6.2 Common Code Blocks: Code blocks defined in methods

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

6.3 Construct Code Blocks

Constructor: A block of code (without modifiers) defined in a class. Also called: Instance code block. Construct code blocks are typically used to initialize instance member variables

class Person3 {
    private String name;//Instance member variable
    private int age;
    private String sex;

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

}

public class TestDemo3 {
    public static void main(String[] args) {
        Person3 p1 = new Person3();
        p1.show();
    }
}


Note: Instance code blocks take precedence over constructor execution.

6.4 Static Code Block

Code block defined using static. Typically used to initialize static member properties.

class Person3 {
    private String name;//Instance member variable
    private int age;
    private String sex;
    private static int count = 0;//Static member variables share data method area by class

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

}

public class TestDemo3 {
    public static void main(String[] args) {
        Person3 p1 = new Person3();
        System.out.println("============");
        Person3 p2 = new Person3();
    }
}


From the run results, the static code block executes first, then the instance code block, and finally the constructor, and the static code block executes only once.

7. Supplementary Instructions

7.1 toString method

class Person2 {//Fields, attributes, member variables
    private String name;
    private int age;
    private String sex;

    //Default constructor constructor object
    public Person2() {
        //this calls the constructor
        this("Hellen", 22, "female");
    }

    //Constructor with 3 parameters
    public Person2(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 TestDemo1 {
    public static void main(String[] args) {
        Person2 p1 = new Person2("James", 10, "female");
        p1.show();
        //We found here that a hash value for an address was printed because the Object's toString method was called
        System.out.println(p1);
    }
}

You can use methods like toString to automatically convert objects to strings

class Person2 {//Fields, attributes, member variables
    private String name;
    private int age;
    private String sex;

    //Default constructor constructor object
    public Person2() {
        //this calls the constructor
        this("Hellen", 22, "female");
    }

    //Constructor with 3 parameters
    public Person2(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);
    }

    @Override
    public String toString() {
        return "Person2{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}


public class TestDemo1 {
    public static void main(String[] args) {
        Person2 p1 = new Person2("James", 10, "female");
        p1.show();

        System.out.println(p1.toString());
    }
}


Matters needing attention:

  1. The toString method is called automatically when println is in use. Converting objects to strings is called serialization.
  2. ToString is a method provided by the Object class, and the Person class we create ourselves inherits from the Object class by default. We can override the toString method to implement our own version of the conversion string method. (Concepts like inheritance and override will be highlighted later.)
  3. @Override is called a "comment" in Java, where @Override indicates that the toString method implemented below is a method that overrides the parent class.The lessons that follow the comment will be covered in more detail.IDEA's fast-generating Object toString method shortcut key:alt+f12(insert)

7.2 Anonymous Objects

Anonymous simply means an object without a name.

  1. Objects that are not referenced are called anonymous objects.
  2. Anonymous objects can only be used when creating objects.
  3. Consider using anonymous objects if an object is used only once and not later
class Person3 {
    private String name;//Instance member variable
    private int age;
    private String sex;

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

    public Person3(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

}

public class TestDemo3 {
    public static void main(String[] args) {
      new Person3("Jenny",45,"female").show();//Calling methods through anonymous objects

    }
}

8. Key Summary

  1. A class can produce an infinite number of objects, classes are templates, and objects are concrete instances.
  2. The properties defined in a class can be divided into several categories: class properties, object properties. 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 are independent of objects, and we can call their attributes or methods only through the class name.
  3. Static code block takes precedence over instance code block execution, and instance code block takes precedence over constructor execution.
  4. The this keyword represents a reference to the current object. Not the current object.

Posted by The Stranger on Sun, 31 Oct 2021 14:15:14 -0700