Java object oriented basic teaching of II

  • 2021-10-16 01:45:06
  • OfStack

Catalog 1. Use access modifiers: 2. static keywords: 3. this keyword summary

1. Use access modifiers:

访问修饰符 同1个类中 同1个包中 子类中 所有类中
private -- -- --
default -- --
protected --
public

Note: private Private default : Default protected Protected public Public

Access control level: private→default→protected→public

2. static keyword:

Keyword: static

Members modified by static are static members, which include static code blocks, static properties, and static methods. A static member does not belong to an object, but only to the class in which the static member belongs.

Static → class

Non-static → object

Static method:

Syntax:


< Access modifier > static  Return type   Method name ( Parameter list ){
    // Method body 
}

Differences between static and non-static methods:

(1) Only static members or methods can be called in static methods, but non-static members or methods cannot be called directly. If you need to call, you need to instantiate them first. (2) Static methods are methods decorated with staitc in a class that are loaded and allocated at the time the class is defined. The non-static method is a method without static keyword, which does not occupy memory when the class is defined. The non-static method is allocated memory only when the object calls the method when the class is instantiated into an object.

3. this keyword

Meaning:

The this keyword always points to the object that calls the method. When using member methods and member properties, you can use "this. Method" and "this. Member Properties" to call the method and member properties of the current object respectively.

Syntax:


this. Method name ;
this. Member attributes ;

Precautions:

1. this () cannot be used in normal methods, but can only be written in constructors

2. Must be the first statement in the constructor

Summarize

That's all for this article. I hope it can help you, and I hope you can pay more attention to this site!


Related articles: