java foundation - detailed explanation of keywords
final static this super
**final keyword
final modifies classes, methods, and variables that are immutable
1.final modified methods cannot be overridden
2. The variable modified by final is a constant. If it is a variable of basic data type, the array will not change once initialized. If it is a variable of reference type, it cannot point to another object after initialization.
3. The class modified by final cannot be inherited. All members of the final class will be implicitly specified as final methods
reason:
-
Lock the method to prevent any inherited class from modifying its meaning;
-
Efficiency. In earlier Java implementations, the final method was turned into an inline call. However, if the method is too large, you may not see any performance improvement brought by embedded calls (the current java version does not need to use the final method for these optimizations).
-
All private methods in the class are implicitly specified as final.
**static keyword
*1, Four usage scenarios:
*1. Modify member variables and member methods
A member modified by static belongs to a class. An object that does not belong to this class is shared by all objects in the class and can be called through the class name (Class.Name)
The member variables declared by static are static member variables, which are stored in the method area in java memory. (Class.Name ; Class.fun())
*2. Static code block
Static code blocks are defined outside the methods in the class, and static code blocks are executed before non static code blocks
(static code block - > non static code block - > construction method)
No matter how many objects are created by this class, the static code block is executed only once.
*3. Static inner classes (static can only modify inner classes if it modifies classes)
There is the biggest difference between static inner classes and non static inner classes:
After compilation, the non static inner class will implicitly save a reference that points to the extranet class that created it, but the static inner class does not.
Without this reference, it means:
- Its creation does not depend on the creation of peripheral classes
- It cannot use non static member variables and methods of any peripheral class
*4. Static guided package (importing static resources, features after jdk1.6)
Basic syntax: import static
You can specify to import the specified static resources in a class, and you do not need to use the class name to call the static member variables in the class. You can directly use the static member variables and member methods in the class
*2, Modify member variables and member methods (common)
The member modified by static belongs to a class. An object that does not belong to a single class is shared by all objects in the class. It can be called through the class name. The member variables declared by static belong to static member variables, which are stored in the method area of Java memory area
Like the Java heap, the method area is a memory area shared by all threads. It is used to store class information, constants, static variables, code compiled by the real-time compiler and other data that have been loaded by the virtual machine. Although the Java virtual machine specification describes the method area as a logical part of the heap, it has an alias called non heap, which should be distinguished from the Java heap.
The method area in HotSpot virtual machine is also often called "permanent generation", which is not equivalent in essence.
Just because the HotSpot virtual machine design team implements the method area with a permanent generation, so that the garbage collector of the HotSpot virtual machine can manage this part of memory like managing the Java heap.
But this is not a good idea, because it is more prone to memory overflow.
Call format:
Class name. Static variable name
Class name. Static method name ()
If a variable or method is private, it means that the property or method can only be accessed inside the class, not outside the class.
public class StaticBean { String name; //Static variable static int age; public StaticBean(String name) { this.name = name; } //Static method static void sayHello() { System.out.println("Hello i am java"); } @Override public String toString() { return "StaticBean{"+ "name=" + name + ",age=" + age + "}"; } } public class StaticDemo { public static void main(String[] args) { StaticBean staticBean = new StaticBean("1"); StaticBean staticBean2 = new StaticBean("2"); StaticBean staticBean3 = new StaticBean("3"); StaticBean staticBean4 = new StaticBean("4"); StaticBean.age = 33; System.out.println(staticBean + " " + staticBean2 + " " + staticBean3 + " " + staticBean4); //StaticBean{name=1,age=33} StaticBean{name=2,age=33} StaticBean{name=3,age=33} StaticBean{name=4,age=33} StaticBean.sayHello();//Hello i am java } }
*Static code block
Static code blocks are defined outside the methods in the class. Static code blocks are executed before non static code blocks (static code blocks - > non static code blocks - > construction methods). No matter how many objects are created, the static code block is executed only once
Basic format
static {
//Statement
}
There can be multiple static code blocks in a class, which can be placed at random. It is not in any method body. The JVM will execute these static code blocks when loading the class. If there are multiple static code blocks, the JVM will execute them in turn according to the order in which they appear in the class, and each code block will be executed only once.
Static code blocks can assign values to static variables defined after them, but they cannot be accessed
*Static inner class
There is the biggest difference between static internal classes and non static internal classes. We know that the non static internal class will implicitly save a reference after compilation, which points to the peripheral class that created it, but the static internal class does not. Without this reference, it means:
Its creation does not depend on the creation of peripheral classes.
It cannot use non static member variables and methods of any peripheral class.
Example (static inner class implements singleton mode)
public class Singleton { //Declare private to avoid calling the default constructor to create objects private Singleton() { } // Declaration as private indicates that the static internal class can only be accessed in the Singleton class private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getUniqueInstance() { return SingletonHolder.INSTANCE; } }
When the Singleton class is loaded, the static inner class SingletonHolder is not loaded into memory. SingletonHolder will be loaded only when getUniqueInstance() method is called to trigger SingletonHolder.INSTANCE. At this time, the INSTANCE is initialized, and the JVM can ensure that INSTANCE is instantiated only once.
This approach not only has the advantage of delayed initialization, but also provides thread safety support by the JVM.
Static guide package
The format is: import static
The combination of these two keywords can specify that the specified static resources in a class can be imported, and the static members in the class do not need to be called with the class name. You can directly use the static member variables and member methods in the class
//Import all static resources in Math. At this time, you can directly use the static methods inside without calling through the class name //If you only want to import a single static method, just replace * with the corresponding method name import static java.lang.Math.*;//Replace with import static java.lang.Math.max; Have the same effect public class Demo { public static void main(String[] args) { int max = max(1,2); System.out.println(max); } }
*Static and non static methods
Static methods belong to the class itself, and non static methods belong to each object generated from the class. If your method performs operations that do not depend on the variables and methods of its class, set it to static (this will make the program take less space). Otherwise, it should be non static.
class Foo { int i; public Foo(int i) { this.i = i; } public static String method1() { return "An example string that doesn't depend on i (an instance variable)"; } public int method2() { return this.i + 1; //Depends on i } } You can call static methods like this: Foo.method1(). If you try to use this method call method2 Will fail. But it works Foo bar = new Foo(1); bar.method2();
Summary:
- Calling static methods eliminates the need to create objects
When calling static methods externally, you can use class name. Method name or object name. Method name
When instantiating a method, only the object name and method name can be used
2. When accessing members of this class, static methods only allow access to static members (i.e. static member variables and static methods), but not instance member variables and instance methods; Instance methods do not have this restriction
**Static {} static code block and {} non static code block (construction code block)
The same point: they are all executed when the JVM loads the class and before the construction method is executed. Multiple can be defined in the class. When defining multiple, they are executed in the defined order. Generally, some static variables are assigned in the code block.
difference:
Static code blocks are executed before non static code blocks (static code blocks - > non static code blocks - > construction methods).
Static code blocks may be executed at the first new object, but not necessarily only at the first new object.
For example, when creating a Class object through Class.forName("ClassDemo"), it will also be executed, that is, new or Class.forName("ClassDemo") will execute static code blocks.
Instead of static code blocks, they are executed every new time.
In general, if some code, such as some of the most commonly used variables or objects of the project, must be executed when the project is started, static code blocks need to be used. This kind of code is actively executed.
If we want to design methods in classes that can be called without creating objects, such as Arrays, Character, String, etc., we need to use static methods. The difference between the two is that static code blocks are executed automatically, while static methods are executed when they are called
public class Test { public Test() { System.out.print("Default construction method!--"); } //Non static code block { System.out.print("Non static code block!--"); } //Static code block static { System.out.print("Static code block!--"); } private static void test() { System.out.print("Content in static methods! --"); { System.out.print("Code block in static method!--"); } } public static void main(String[] args) { Test test = new Test(); Test.test();//Static code block-- Content in static method-- Code block in static method-- } } Static code block!--Non static code block!--Default construction method!--Content in static methods! --Code block in static method!--
When only Test.test() is executed; Output when:
Static code block! – Content in static method-- Code blocks in static methods! –
When only test = new test(); Output when:
Static code block! – Non static code block! – Default construction method! –
Summary:
The difference between non static code blocks and constructors is:
Non static code blocks are used to initialize all objects uniformly, while constructors are used to initialize the corresponding objects, because multiple constructors can be used. Which constructor will create what kind of objects,
However, no matter which object is created, the same construction code block will be executed first. In other words, the initialization contents common to different objects are defined in the construction code block.
**this keyword
this is used to reference the current instance of the class
class Manager { Employees[] employees; void manageEmployees() { int totalEmp = this.employees.length; System.out.println("Total employees: " + totalEmp); this.report(); } void report() { } }
Usage:
This.employment.length: access the variable of the current instance of the Manager class;
this.report(); Call the method of the current instance of the Manager class;
**super keyword
super is used to access the methods and variables of the parent class from the child class
public class Super { protected int number; protected showNumber() { System.out.println("number = " + number); } } public class Sub extends Super { void bar() { super.number = 10; super.showNumber(); } }
The Sub class accesses the parent class member variable number and calls the showNumber () method of its parent class super
this and super questions:
-
When using super() in the constructor to call other constructor methods in the parent class, the statement must be on the first line
-
When this calls other construction methods, it needs to be put in the first place
(because the initialization action must be executed first. If the initialization also contains initialization, the internal initialization must be executed first. At the same time, one constructor can be called with this, but two this cannot be called (this call construction method can only be placed in the first line of the constructor))
this keyword summary -
this super cannot be used in static methods
reason:
5. The member modified by static belongs to a class, not only an object of a single class, but also shared by all objects in the class.
6. This represents a reference to this class of objects and points to this class of objects
7. super represents the reference to the parent class and points to the parent class object
8. this and super belong to the object category, and static methods belong to the class category