Java classes and objects

1, Object oriented and process oriented

Object oriented is one of the most popular programming methods. Almost all applications are object-oriented now. The earliest concept of object-oriented was actually put forward by IBM and applied in the Smaltalk language in the 1970s. Later, according to the object-oriented design idea, C + + was formed, and Java, an object-oriented programming language, was produced by C + +.

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 functional realization through logic
Facing the process: 1. Open the refrigerator 2. Put the elephant in 3. Close the refrigerator
Object oriented: opening, storing and closing the refrigerator are the operation of the refrigerator and the 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 features:

  1. Object oriented is a common idea, which is more in line with people's thinking habits;
  2. Object oriented can simplify complex business logic and enhance code reusability;
  3. Object oriented has the characteristics of abstraction, encapsulation, inheritance, polymorphism and so on.

2, Classes and objects

1. Preliminary understanding of class and object

  • Class: class is the general name of a class of objects;
  • Object: an object is an instance of this kind of materialization.

Simple example: the model we use to make moon cakes is a class, and the model can be used to make moon cakes. In this example, the class is the model
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

2. Definition and use of classes and 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 classes. The syntax is as follows:

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

For example, define a Person class

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

  3. Class instantiation

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

Take an 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();
        //Generate object instantiation object
        Person person2 = new Person();
        Person person3 = new Person();
    }
}

  The output result is:

having dinner!
sleep!

be careful:

  • The new keyword is used to create an instance of an object
    Format: class name object name = new class name ();
  • Use. To access properties and methods in objects;
  • You can create multiple instances of the same class.

4. Members of the class

Class members can include the following: fields, methods, code blocks, internal classes, interfaces, and so on.  

four point one   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" (all three names can be used, which are generally not strictly distinguished)

For example, chestnuts:

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

  be careful:

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

  •   The default value is 0 for various numeric types
  • 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

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);
    }
}
// results of enforcement
//Zhang San
//18

four point two   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. I'm 18 years old

  be careful:

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

four point three   static keyword

  • Modifier attribute
  • Modification method
  • Code block
  • Modifier class

Modified attributes, Java static attributes are related to classes and independent of specific instances. In other words, different instances of the same class share the same static attribute.
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
    }
}
public class Main{
    public static void main(String[] args) {
        TestDemo.change();//Can be called without creating an instance object
        System.out.println(TestDemo.count);
    }
}

  The output result is:

100

be careful:

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)

4.4 memory layout  

  • Heap memory: stores the attribute contents of an object. Heap memory needs to allocate space with the new keyword;
  • Stack memory: stores the address of heap memory.
  • Method area: store class binary files. Contains class information, static variables, and constant pools (String strings, constant values decorated with final, etc.)

In any case, as long as you see the keyword new, it means that you want to allocate a new heap memory space. Once the heap memory space is allocated, there will be attributes defined in the class, and the attribute content is the default value of its corresponding data type.  
Static member variables decorated with static are stored in the method area.

3, Encapsulation

Some information of the class is hidden inside the class, which is not allowed to be directly accessed by external programs. Instead, the operation and access of hidden information are realized through the methods provided by the class

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

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");
    }
}
// results of enforcement
//My name is Zhang San. I'm 18 years old
  • Such code causes the user of the class (the code of the main method) 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 name to myName), the user of the class needs to modify his code on a large scale, and the maintenance cost is high

Use private to encapsulate attributes and provide public methods for class callers:

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. I'm 18 years old
  • At this time, the field has been decorated with private. The caller of the class (in the main method) cannot use it directly. Instead, you need to use the show method
    At this point, 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)

be careful:

  •   private can modify not only fields, but also methods
  • Generally, we will set the field as private attribute, but whether the method needs to be set as public depends on the specific situation
    It is expected that a class only provides "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.

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

A compilation error occurs:
Test.java:13: error: age can access private in Person
person.age = 20;

  At this time, if you need to obtain or modify this 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);
    }
}
class Test {
    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

be careful:

  • 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

4, Construction method  

1. Basic grammar

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.

new execution process:

  • Allocate memory space for objects
  • Call the constructor of the object

  rule of grammar:

  • The method name must be the same as the class name
  • Constructor has no return value type declaration
  • 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)  

be careful:

  • 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

For example, chestnuts:

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

  Execution results:

name: caocao age: 10 sex: male
name: zhangfei age: 80 sex: male

2.this keyword

  • this modifier attribute.
  • this modification method.
    Syntax: this (construction method parameter list)
  • this represents a reference to the current object.

  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);
    }
}
    public class Main{
        public static void main(String[] args) {
        Person person = new Person();//Calling a constructor without parameters
        person.show();
    }
}
// results of enforcement
//name: bit age: 12 sex: man

5, Code block

1. What is a 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:

  • Common code block
  • Tectonic block
  • Static block
  • Synchronous code block

  2. Common code block

Normal code block: a code block defined in a method

public 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);
    }
}
// results of enforcement
//x1 = 10
//x2 = 100

  3. Construct code blocks

Building blocks: blocks of code defined in a class (without modifiers). 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
    {
        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 Main {
        public static void main(String[] args) {
        Person p1 = new Person();
        p1.show();
    }
}
// Operation results
//I am instance init()!
//I am Person init()!
//name: bit age: 12 sex: man

  Note: instance code blocks take precedence over constructor execution.

4. Static code block

Code blocks defined using static. 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 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);
    }
}
public class Main {
    public static void main(String[] args) {
        Person p1 = new Person();
        Person p2 = new Person();//Will static code blocks still be executed?
    }
}

be careful:

  • 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

Summary:

  • 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
  • Methods are called class methods, which are characterized by being independent of objects. We can call their properties 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.
     

Tags: Java Back-end

Posted on Fri, 22 Oct 2021 08:57:42 -0400 by zigizal