Java classes and objects

Posted by geebo on Sat, 19 Feb 2022 22:23:26 +0100

object-oriented

encapsulation

One of the core ideas of object-oriented programming is to encapsulate data and operations on data. Through abstraction, common properties are extracted from concrete examples to form general concepts, such as the concept of classes.

  People often talk about the motor vehicle class is a concept formed by extracting common attributes and functions from specific examples. Then a specific car is an example of the motor vehicle class, that is, the object.

  An object encapsulates its own data and the operation of these data reasonably and effectively. For example, each car calls "acceleration" and "deceleration" to change its own running speed.

inherit

Inheritance embodies an advanced programming mode of undertaking history. A subclass can inherit the attributes and functions of the parent class, that is, it inherits the data and operations of the parent class, and can add the unique data and operations of the subclass at the same time.

polymorphic

Polymorphism is another important feature of object-oriented programming.
There are two meanings of polymorphism.
One is the polymorphism of operation name, that is, multiple operations have the same name, but the parameter types received by these operations must be different.
Another kind of polymorphism is related to inheritance, which means that the same operation may produce different behaviors when called by different types of objects.

Class definition

The syntax format of class definition is as follows:
[class modifier] class name [extends parent class name]
{... / / class body}
1. Class modifier: defines the access characteristics between classes.
2. Extensions: represents the parent class of the declared class inheritance.
If there is no extensions declaration part, it means that the declared class inherits from the java root class Object (by default).
Example: public class Circle extends object{
......
}
3. Class body: declare the members of the class, including member variables, member methods and constructors.

class Vehicle{ 
     int speed;                          	            //Member variable definition
     float weight,height;                               //Member variable definition
     public Vehicle(){                                                              //Class constructor
      }
     void changSpeed(int newSpeed){        //Member method definition
         speed=newSpeed;
     } 
     float getWeight(){                      	//Member method definition
        return weight;
     }
     float getHeight(){                      	//Member method definition
        return height;
     }
}

Member variable

Member variable (domain)
The data properties of a class are defined by its member variables (fields). Declare a field in the class in the form of:
[member variable modifier] type member variable name;

 Member variable modifiers include public,private, protected,package(default),static and final Wait.

What is package permission?
That is, all classes in the same package can access, while classes outside the package cannot access the variable.

static

 static What's a modifier for?
 One sentence description is: it is convenient to call without creating an object(method/variable). 

Each object of a class has its own (called instance variable).
All objects belong to a class.
Class variables should be declared with the keyword static. Such class variables can also be called static variables, and the corresponding member methods modified by static are called static methods, which are collectively referred to as static members of the class.

//For example, in the following Student class, name is the instance variable and count is the class variable.
public class Student{
       String name;
       static int count;    //Shared by all objects
   }
      Class variables are data variables associated with a class, that is, class variables are variables associated with all objects created by the class.
     Changing the class variable of one object changes the class variable of other objects at the same time.
     You can access not only the object name, but also the class name.
The use format of static members of a class is generally:

Object Static variable name;
Class name Static variable name;
Object Static method name ();
Class name Static method name ();

class Main{
    public static void main(String [] args){
        System.out.println(A.a); // 0
        System.out.println(A.b); // report errors
    }
}
class A{
    static int a = 0;
    int b = 0;
}
class Main{
    public static void main(String [] args){
        System.out.println(A.a);
        A a = new A();
        a.a = 15;
        System.out.println(a.a + " " + A.a);
    }
}
class A{
    static int a = 0;
    int b = 0;
}
/*
0
15 15
*/

final

The member variable modified by final can only be assigned once and can only be assigned an initial value, and the initial value must be assigned when defining, otherwise an error will be reported.

class Main{
    public static void main(String [] args){
        A a = new A();
        // a.c = 15; //  report errors
        System.out.println(a.c);
    }
}
class A{
    final int c = 0;
}

method

Methods generally operate on data members in a class.
If the data member in the class is private, a public method is often defined to set the value of the data member or read the value of the data member.

Construction method

The constructor name is the same as the class name.
Constructors are generally used to initialize objects of a class.
When the program creates the object of the crack class, the new operator allocates memory for the object and calls the constructor to initialize the object, that is, assign initial values to each member variable of the object in the constructor by calling the constructor of the crack class.

Define initialization and constructor initialization

class Main{
    public static void main(String [] args){
        A x = new A(5);
        System.out.println(x.a);
    }
}
class A{
    int a = 5;
    A(int a) {
        this.a += a;
    }
}
/*
10
*/
//You can see that the initialization of the definition of this object is before.
//Is defined before the initialization of the real constructor.

A class can also have multiple construction methods (overload of construction methods). If the user does not define the construction method, there is a default empty construction method in the method area.
When you customize the construction method, the original construction method will be overwritten by default.

class Main{
    public static void main(String [] args){
        A x = new A(1, 2);
        A y = new A();
    }
}
class A{
    int a;
    int b;
    A (int a, int b) { // User defined construction method.
        this.a = a;
        this.b = b;
    }
    A () { // Default construction method
        
    }
}

Scope of class

In Java, according to the role and relevance of classes, a large number of classes are grouped (packages), and each group has a name called package name.

Classes in the same package can access each other, while whether classes in different packages can access each other depends on the scope of the class. Except for private decorated classes

The scope modifier of a class tells us the access characteristics between classes.

There are two scope modifiers for a class, which should be placed in front of the class keyword.


The default here is that the class is not modified by default, that is, only the classes inside the package can be accessed.
We are talking about whether a class can be accessed or not, that is, whether the object of another class can be declared in the method of the class.

Comments on classes in java

JavaDoc comments in java:

/**
*
*
*
*
*/

This is the annotation that can describe each attribute method of a class in java.

Member access control


What is member access control?
Member access control is used to control whether members in the current class can be accessed in other classes.
How to understand: that is, whether members of this class can be called through the object of the current class created in other classes, which is declared by the member access control modifier.

Method parameter transfer

① When the parameter of the method is a simple data type, the value of the actual parameter is passed to the formal parameter;
② When the parameter of the method is a composite data type (object), the value of the argument is passed to the formal parameter, which points to the same heap address as the argument.

Cricle cricle1,cricle2;

cricle1=new Cricle (100);

cricle2=new Cricle (200);

cricle1=circle2;



// When the parameter of the method is an object, it is not just a simple value transfer, but an address transfer
class Main{
    public static void main(String [] args){
        A x = new A(1);
        B b = new B();
        b.print(x);
        System.out.println(x.a);
    }
}
class A{
    int a;
    A (int a) {
        this.a = a;
    }
}
class B{
    void print(A a) {
        a.a = 12;
        System.out.println(a.a);
    }
}
/*
12
12
*/

Method overloading

Java supports method overloading. Method overloading is defined as defining multiple methods with the same name in a class. The return types of methods are exactly the same. The difference is that the overloaded method parameters must be different:
① The types of parameters are different.

② The order of parameters is different. This refers to the case where a method has multiple parameters of different types. Changing the order of parameters is also a distinguishing method.

③ The number of parameters is different. The number of overloaded method parameters in the following example is one, two and three respectively.

class Main{
    public static void main(String [] args){
        A x = new A();
        x.f1(10);
        x.f1("12");
    }
}
class A{
    int a;
    void f1(int a) {
        System.out.println("f1");
    }
    void f1(String a){
        System.out.println("f2");
    }
}
// The method overload here conforms to the first case above, and the other cases are similar to this case.

The use of this keyword in construction method

class Main{
    public static void main(String [] args){
        A x = new A(5);
        System.out.println(x.a);
    }
}
class A{
    int a = 5;
    A(int a) {
        this.a += a; 
        // this.a represents the attribute variable of the class rather than the local variable in the method. This is used to distinguish it here
    }
}

Garbage can in java

java memory usage

1. Stack memory: used to store some basic types of variables and reference variables of objects defined in functions. When the scope of the variable is exceeded, java will automatically release the memory space allocated for the variable, and the memory space will be used for other purposes.

2. Heap memory: used to store objects and arrays created by new. The objects and arrays created by new in the heap are pointed to by the reference variables defined in the stack. The value of the reference variable is the first address of the array or object in the heap memory. The reference variable is released after the program runs outside its scope. At this time, the arrays and objects in the heap become garbage when there is no reference variable pointing to it.

// Turn an object into garbage with code
class Main{
    public static void main(String [] args) {
        A x = new A();
        x = null;
    }
}
class A{
    int a = 5;
    
}
// At this time, x has become garbage, waiting for space to be recycled.

garbage collector

When an object becomes garbage, the garbage collector will be enabled at a later time to reclaim the space occupied by these heap memory garbage, but the enabling time is not controlled by the programmer and there is no rule to follow. It will not be aroused as soon as garbage is generated, and it may even have no chance to start when the program terminates. Therefore, this is not a very reliable mechanism.
We can also call system at any time in the program GC () method to explicitly run the garbage collector.
For example, run the garbage collector after creating a lot of garbage code or before you need a lot of memory code to clear objects that are no longer referenced in memory.

finalize

Before an object is garbage collected (whether explicitly or automatically), the garbage collector gives the object a chance to call its own finalize method. This process is called object undo method.
The finalize method is a method of the Object class. Any Object can automatically use this method through class inheritance. This method will be called before it is recycled as a garbage Object.

Class method and instance method

Methods in a class can call each other:
Instance methods can call instance methods or class methods in this class; Class methods can only call class methods of this class, not instance methods;
At the same time, this keyword cannot be used in class methods.
Whether it is instance variable or class variable, it can be operated in instance method; Class methods can only operate on class variables, not instance variables, that is, class methods cannot have statements that operate on instance variables,
Why is there such a difference between the two?
(1) Instance methods must be called through objects
(2) Class methods can be called by class name. At this time, no object may be born.

// How to record how many objects are created
class Main{
    public static void main(String [] args) {
        A x = new A(0);
        A y = new A(0);
        A z = new A(0);
        A w = new A(0);
        System.out.println(A.count);
    }
}
class A{
    int a;
    static int count = 0;
    A(int a) {
        count ++;
        this.a = a;
    }
}
/*
4
*/

static code block

Static code block refers to the code block wrapped by static {}. The variables in the static code block are local variables, which are executed only once when the class is loaded, no matter how many times the class is instantiated
However, when the class is not instantiated, the static code block will not be executed once

class Main{
    public static void main(String [] args) {
        A x = new A();
        A y = new A();
        A z = new A();
        A w = new A();

    }
}
class A{
    int a;
    static int b = 0;
    static {
        A.b = 5;
        System.out.println(A.b);
    }
    static {
        System.out.println("NO.2");
    }
}
/*
5
NO.2
*/
class Main{
    public static void main(String [] args) {
        

    }
}
class A{
    int a;
    static int b = 0;
    static {
        A.b = 5;
        System.out.println(A.b);
    }
    static {
        System.out.println("NO.2");
    }
}
//No output.
Static code blocks can be used to initialize classes and constructors can be used to initialize objects. There can be multiple static code blocks in a class when there are multiple static code blocks in a class static Code blocks are executed in sequence.

Even if the class contains the main function, it still executes the static code block to initialize the class first, and then executes the main function    

Static code block refers to the code block wrapped by static {}. The variables in the static code block are local variables, which are executed only once when the class is loaded, no matter how many times the class is instantiated

Static code blocks can be used to initialize classes, constructors can be used to initialize objects, and there can be multiple static code blocks in a class

Even if the class contains the main function, it still executes the static code block to initialize the class first, and then executes the main function    

Construct code block

Construction code block refers to the code block wrapped with {}. The construction code block is to initialize all objects uniformly. The construction code block defines the initialization contents common to different objects

For a class, execute in the following order:

Execute static code block, construct code block, constructor

For static variables, static initialization blocks, variables, initialization blocks and constructors, their initialization order is (static variables, static initialization blocks) > (variables, construction code blocks) > constructors.

//When there are multiple construction methods of a class, we can use the construction code to count the number of created objects
public class Client {
    public static int count = 0;
    {
        count++;
    }

    public Client() {

    }

    public Client(int i) {
        this();
    }

    public Client(String string) {
    }

    public static void main(String[] args) {
        new Client();
        new Client(1);
        new Client("1");
        System.out.println(Client.count);
    }
}

Precautions for using static

When using static methods or static variables of classes, pay attention to the following points:

Local variables in any method body cannot be declared static.

class Main{
    public static void main(String [] args) {
        static int a = 5; // Because main is static, the statement cannot be executed. Compilation error.
    }
}

Static methods cannot reference this and super keywords in any way.

class Main{
    public static void main(String [] args) {
        
    }
}
class A{
    int a;
    static int b = 0;
    static {
        this.b = 5; // this keyword is used under the static constructor, and an error is reported.
    }
}

Static methods can only directly call other static members of the same class (including methods and variables), but can not directly access non static members in the class.

class Main{
    public static void main(String [] args) {

    }
}
class A{
    int a;
    static int b = 0;
    static {
        a = 5; // Compilation error
    }
}

The main() method is static, so the non static members of the class cannot be accessed directly in the main() method. You must create an instance object of the class before accessing the non static members of the class through this object.

Enumeration type

Enum type is a special data type that defines a predefined list of enum constants
Using ordinary key value pair constants can limit the results, but cannot limit the range of input variables
Enumeration can limit the use range of variables through predefined enumeration constants

For example, week, month, direction, planet, etc

class Main{
    public static void main(String [] args) {
        Season[] a = Season.values();
        for(Season i : a) {
            
        }

    }
    public enum Season{
        SPRING(1), SUMMER(2), AUTUMN(3), WINTER(4);
        private int code;
        Season(int c) {
            this.code = c;
        }
    }
}

Topics: Java