java objects and classes

catalogue

1, Class definition

2, this reference

3, Construction method and object initialization

1. Construction method

2. Object initialization

4, Encapsulation

5, Package

1. Concept of package

2. Import classes in package

3. Custom package

4. Common packages

6, static member

1. static modifier member variable

2. Static member method

7, Code block

8, Object printing

9, Inner class

1. Instance inner class

2. Static inner class

3. Local inner class

1, Class definition

1. The class keyword is required to define a class in java

class ClassName{
   filed; //Member variables (properties)
   method; //Member method
}

[note]

  • The class name is defined by the big hump
  • Generally, only one class can be defined in a file
  • The class where the main method is located should generally be decorated with public
  • The class decorated by public must be the same as the file name
  • You cannot modify the name of the class decorated by public

2. Class usage (instantiation)

Defining a class is equivalent to defining a new type in the computer. The process of creating an object with the defined class type is called class instantiation.

//Defines a dog
class PetDog {
    public String name;//name
    public String color;//colour
    public void barks() {
        System.out.println(name + ": Wangwangwang~~~");
    } 
    public void wag() {
        System.out.println(name + ": Wag your tail~~~");
    }
}
public class Main{
    public static void main(String[] args) {
        PetDog dogh = new PetDog(); //Instantiate objects through new
        dogh.name = "Ah Huang";
        dogh.color = "Black and yellow";
        dogh.barks();
        dogh.wag();
}

[note]

  • The new keyword is used to create an instance of an object
  • Use [class name. Member / method] to access the object
  • Multiple instances of the same class can be created

2, this reference

The java compiler adds a hidden reference type parameter (this) to each "member method", which points to the current object (the object that calls the member method when the member method is running). The operation of all member variables in the member method is accessed through this reference. (this refers to the object that calls the member method)

There are three uses of this:

  • this. Member variables (member variables cannot be static)
  • this. Member method (member method cannot be static)
  • this() calls other constructor methods (must be placed on the first line)

For the following codes:

public class Date {
    public int year;
    public int month;
    public int day;

    public void setDay(int y, int m, int d) {
        year = y;
        month = m;
        day = d;
    }
    public void printDate() {
        System.out.println(year + "/" + month + "/" + day);
    }
    public static void main(String[] args) {
// Construct three date type objects D1, D2, D3
        Date d1 = new Date();
        Date d2 = new Date();
        Date d3 = new Date();
// Date setting for d1, d2 and d3
        d1.setDay(2020, 9, 15);
        d2.setDay(2020, 9, 16);
        d3.setDay(2020, 9, 17);
// Print content in date
        d1.printDate();
        d2.printDate();
        d3.printDate();
    }
}

(1) The formal parameter name is the same as the member variable name

According to the principle of local variable priority, the year in the method is the parameter year of the method. The number of compilation times cannot pass. You need to call the member variables in the class through this.

public void setDay(int year, int month, int day){
   this.year = year;
   this.month = month;
   this.day = day;
}

(2) When the three objects are calling the methods setDate and printDate, the function cannot determine that the data of that object is printed. At this time, this is required to determine the printing object.

public void printDate(){
    System.out.println(this.year + "/" + this.month + "/" + this.day);
}

[note]

  • this can only be used in member methods
  • Type of this: the reference type of the corresponding class
  • In the "member method", this can only refer to the current object and cannot refer to other objects. It has the attribute of final (equivalent to const in C + +)
  • this cannot be empty

3, Construction method and object initialization

1. Construction method

Is a special membership method. The name must be the same as the class name. When creating an object, it is called automatically by the compiler and only once in the whole object's life cycle.

[Characteristics]

  • The name must be the same as the class name.
  • There is no return value type, and it is not allowed to set it to void.
  • At least one construction method can be multiple.
  • The compiler calls automatically when an object is created and only once in the object's life cycle.
  • Construction methods can be overloaded. (construction methods of different parameters can be provided according to their own needs)
public class Date {
    public int year;
    public int month;
    public int day;
    // Nonparametric construction method
    public Date() {
        this.year = 1900;
        this.month = 1;
        this.day = 1;
    }
    // Construction method with three parameters
    public Date(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
}

When calling an object, the constructor is called according to the parameters of the object.

  • If no constructor is defined, the compiler will generate a default constructor, which must be parameterless. Once the construction method is defined by the user, the compiler will no longer generate.
  • You can use this in one constructor to call another constructor.
public class Date {
    public int year;
    public int month;
    public int day;
    //Construction method without parameters
    public Date(){
        this(1900, 1, 1);
        System.out.println(year);
    } 
    // Construction method with three parameters
    public Date(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
}

[note]

  1. this must be the first statement in the constructor.
  2. Cannot form a ring
  • In most cases, public modification is used, and private modification will be used in special situations

2. Object initialization

(1) Default initialization

Local variables must be initialized when used, while member variables are not. Because new will call the construction method to assign values to each member in the object.

Work of new keyword in virtual machine:

  • Check whether the class corresponding to the object is loaded
  • Allocate memory space for objects
  • Handle concurrency problems (multiple threads apply for space at the same time, and the JVM should ensure that the space allocated to the object does not conflict)
  • Initialize allocated space
  • Set object header information
  • Call the construction method to assign values to each member in the object

(2) Local initialization

When declaring a member variable, the initial value is given directly.

4, Encapsulation

Three characteristics of object-oriented program: encapsulation, inheritance and polymorphism.

Encapsulation: from the syntax level, it is to modify the field or method with private so that it can only be used in the current class, which plays the role of encapsulation

[access qualifier]

Java mainly realizes encapsulation through classes and access rights: classes can combine data and methods to encapsulate data, and access rights are used to control whether methods or fields can be used directly outside the class. Java provides four access permissions:

Rangeprivatedefaultprotectedpublic
The same class of the same package

Different classes of the same package
Subclasses in different packages
Non subclasses in different packages

For private modified variables, we can get and manipulate them through get and set methods.

(right click → Generate → GetterandSetter)

public class Computer {
    private String cpu;// cpu
    public String getCpu() {
        return cpu;
    }
    public void setCpu(String cpu) {
        this.cpu = cpu;
    }
}

[description]

  • protected is mainly used in inheritance
  • Default permission: the default permission when nothing is written
  • In addition to limiting the visibility of members in the class, access permissions can also control the visibility of the class
     

[note] in general, the member variable is set to private and the member method is set to public

5, Package

1. Concept of package

Software package: for thicker management classes, multiple classes are collected together into a group, which is called package.

Classes with the same name are allowed in the same project as long as they are in different packages.

2. Import classes in package

Use the import statement to import the package.

import java.util.Date;
public class Test {
    public static void main(String[] args) {
        Date date = new Date();
        // Get a millisecond timestamp
        System.out.println(date.getTime());
    }
}

If necessary, use Java For other classes in util, you can use import Java uti.*

For the following cases:

import java.util.*;
import java.sql.*;
public class Test {
    public static void main(String[] args) {
        java.util.Date date = new java.util.Date();
        System.out.println(date.getTime());
    }
}

There is a Date class in both packages. At this time, we need to refer to the complete class name, otherwise the compiler does not know which package to call.

3. Custom package

[basic rules]

  • Add a package statement at the top of the file to specify the package where the code is located
  • The package name shall be specified as a unique name as far as possible, usually in the inverted form of the company domain name
  • The registration should match the code path
  • If a class does not have a package statement, the class is placed in a default package

[new package] right click src → new package

[new class] right click package name → new class

4. Common packages

  • Java.lang: the compiler of common basic classes (String and Object) of the system will import them automatically
  • java.lang.reflect: java reflection package
  • java.net: network programming development package
  • java.sql: support package for database development
  • java.util: tool package provided by Java
  • java.io: I/O programming development kit

6, static member

In Java, members modified by static are called static members or class members. They do not belong to a specific object and are shared by all objects.

Static member variables and member methods are object independent

1. static modifier member variable

[static member variable characteristics]

  • It does not belong to a specific object, but is the attribute of a class. What is shared by all objects is not stored in the space of an object
  • It can be accessed through objects or classes. Class access is recommended
  • Class variables are stored in the method area
  • The life cycle is accompanied by the life of the class (created with the loading of the class, unloaded and destroyed with the unloading of the class)

2. Static member method

[static member method characteristics]

  • It does not belong to a specific object, but is a class method
  • Pass the class name Static method name (...) mode call
  • You cannot access any non static member variables in a static method (the static method has no hidden this reference parameter)
public static String getClassRoom(){
        System.out.println(this);
        return classRoom;
} 
// Compilation failure: Error:(35, 28) java: cannot reference non static variable this from static context
public static String getClassRoom(){
        age += 1;
        return classRoom;
} 
// Compilation failure: Error:(35, 9) java: cannot reference non static variable ag from static context
  • No static method can be invoked in static methods. (non static methods have this parameters, which cannot be passed in static methods).

7, Code block

[note] execution sequence of code blocks:

Static code block (only executed once) → instance code block → construction method

public class Student{
        private String name;   //Instance member variable
        private String gender;
        private int age;
        private double score;
        private static String classRoom;
        //Instance code block
        {
            this.name = "bit";
            this.age = 12;
            this.gender = "man";
            System.out.println("I am instance init()!");
        }
        // Static code block
        static {
            classRoom = "bit306";
            System.out.println("I am static init()!");
        }
        public Student(){
            System.out.println("I am Student init()!");
        } 
        public static void main(String[] args) {
            Student s1 = new Student();
            Student s2 = new Student();
        }
}

1. Normal code block: a code block defined in a method

2. Construction code block: a code block defined in a class. Also known as instance code block, it is generally used to initialize instance member variables

It is defined inside the class and is at the same level as the constructor.

3. Static code block: a code block decorated with static. Generally used to initialize static member variables

[note]

  • No matter how many objects are generated, the static code block is executed only once
  • Static member variables are attributes of classes. Loading classes in the JVM opens up space and initializes
  • If a class contains multiple static code blocks, when compiling the code, the compiler will merge them according to the defined order and finally place them in the generated < > method, which will be called only once when loading the class.
  • The instance code block is executed only when the object is created

8, Object printing

When there are multiple member variables in the class, we need to print the contents of the object. At this time, we should override the toString method.

(right click → Generate → toString())

 public class Person {
        String name;
        String gender;
        int age;
        public Person(String name, String gender, int age) {
            this.name = name;
            this.gender = gender;
            this.age = age;
        } 
        @ Override
        public String toString() {
            return "[" + name + "," + gender + "," + age + "]";
        } 
        public static void main(String[] args) {
            Person person = new Person("Jim","male", 18);
            System.out.println(person);
        }
    } // Output result: [Jim, male, 18] 

When we call system out. println(); When,

The compiler will call the toString method of Object by default. If the current class overrides the toString method, it will call its own toString method. (Rewriting requires @ Override to check.)

9, Inner class

In java, a class can be defined inside another class or a method. The former is called an internal class and the latter is called an external class. Inner classes are also an embodiment of encapsulation.

1. Instance inner class

A class defined in a class and not modified by static

[note]

  • Create internal class object

OutClass.InnerClass  innerClass=new OutClass().new InnerClass();

External class Internal class variable = reference of external class object new inner class ()

  • In the internal class of the instance, the created member variable cannot be static. If it is defined, it can only be static final
  • If the internal class and the external class have members with the same name, the priority access is the internal class
  • If you need to access the member variable with the same name of the external class, you must (external class name. this. Member with the same name)

2. Static inner class

Internal member class modified by static

[note]

  • Create a static inner class object

OutClass.InnerClass innerclass=new OutClass.InnerClass();

  • When creating static internal class objects, you do not need to create external class objects first
  • The internal class of the member will generate an independent bytecode file after compilation. The naming format is: external class name Internal class name
  • In a static inner class, only static members of the outer class can be accessed

3. Local inner class

In the method defined in the external class, this internal class can only be used in the defined position, and it is generally used very rarely

[note]

  • Local inner classes can only be used within a defined method body
  • Cannot be modified by public, static and other modifiers
  • Hardly used

Keywords: Java Back-end

Added by cdc5205 on Thu, 24 Feb 2022 11:51:55 +0200