Technology Sharing

Two Java interview questions every day (Part 1)

2024-07-11

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1. The difference and connection between this keyword and super keyword

The this keyword is used within this class.

Within a class, you can use this to refer to the current object in any method.

The this keyword is used to resolve conflicts between global variables and local variables.

this() can call the overloaded constructor of the same class and needs to be placed in the first line.

The super keyword is used in subclasses.

In the subclass, you can call the methods and properties of the parent class through super.

super() can call the constructor in the parent class and needs to be placed in the first line.

super() and this() cannot be used at the same time, and neither can be used in static methods.

2. The difference between final keyword and static keyword

final modifies variables, methods, and classes

If the variable is modified by final, the variable is a constant, which cannot be modified and must be initialized when defined.

If the method is modified as final, it cannot be overridden by subclasses.

If a class is modified with final, it cannot be extended and cannot have subclasses. String and Math in the Java class library are final classes.

Final modifier reference type constant

If the constant is a basic data type, it cannot be modified.

If the constant is a reference type, you cannot assign other objects to the reference, but you can use the reference to change the internal properties of the object.

A variable modified by static is a static variable, which is essentially a global variable. All instances of a class share the same static variable. Therefore, after modifying the value of a static variable through an object, the static variable accessed by other objects of the class is the modified value. When a class is loaded by the virtual machine, the static variable is initialized, and you can use the static variable without creating an object of the class.

Methods modified with static are static methods. They can only call other static methods directly, can only access static data directly, and cannot reference the this or super keywords in any way.

The code block modified by static is a static code block, which is executed only once and is executed when the class is loaded. Its function is to statically initialize data.