Preface
Keywords in Java In the previous article, we talked about final
, in-depth understanding of the final keyword in Java
, This time we will review this
and super
. As a Java programmer, I think the foundation is the most important, because it determines our upper limit, so most of my articles are still shared The basic knowledge of Java is the main, and I learn the basics well. I want to learn the latter knowledge easily. Not much nonsense, enter the text.
this
The this keyword can only be used inside a method and represents a reference to calls the method.
In fact, in simple terms, the this keyword means the current object. Let's introduce the usage of this keyword in Java.
1. Call member variables
Inside a method of a class, if we want to call its member variables without this, what would we do?
public class ThisTest {
private String name = "xiaoming";
public String getName() {
return name;
}
public void setName(String name) {
name = name;
}
}
Looking at the above code, we created a name
ThisTest
class, and then created a setName
method. Note that the formal parameter of this method is also String name
, so if we assign the value to name = name
, will it change the attribute of the name
public static void main(String[] args) {
ThisTest thisTest = new ThisTest();
thisTest.setName("xiaoma");
System.out.println(thisTest.getName());
}
The printed result is xiaoming
instead of the xiaoma
we reset. Obviously, this method cannot call member variables inside the method. Because the parameter name and the name of the member variable of the same, setName
internal method name = name
, according to a recent principle, the compiler defaults to the two name
attributes are parsed as parameter name
, resulting in operation and we set the value of the member variable name
complete It doesn't matter, of course it can't be set.
The solution is to use the this keyword. We modify the setName method as follows:
public void setName(String name) {
this.name = name;
}
After calling the main method above for assignment, the printed result is xiaoma
.
this represents the current object, that is, the object that calls the method, and the object .name
must be the member variable that is called.
2. Call the constructor
The constructor is a method with the same name as the class. The constructor has no return value, but it cannot be modified with void. In a class, there must be a constructor, if not, the compiler will automatically add a no-argument constructor for this class when compiling. A class can have multiple construction methods, which are distinguished according to the parameters when they are called.
public class Student {
private int age;
private String name;
public Student() {
this("小马",50);
}
public Student(String name, int age) {
this.name = name;
this.age = age;
System.out.println(name + "今年" + age + "岁了");
}
public static void main(String[] args) {
Student student01 = new Student();
Student student02 = new Student("小军",45);
}
}
Through this ("little horse", 50) to call another construction method
Student(String name, int age)
to initialize and assign member variables.
Output result:
小马今年50岁了
小军今年45岁了
Process finished with exit code 0
Note: To call the constructor through this, you can only put this code on the first line of the constructor. This is the compiler's rule, as shown below: Putting it on the second line will cause an error.
3. Call ordinary methods
This represents the current object, so it must be able to call ordinary methods of the current class.
public Student() {
this.say();
}
public void say(){
System.out.println("小马很会唱歌。");
}
4. Return the current object
public class ThisTest {
public Object newObject(){
return this;
}
}
This means that whoever calls the newObject() method will return whose reference.
super
The super keyword in Java is a reference to the parent class object.
We analyze the reference of parent class object, which means that we can only use it in subclasses when we use it. Since it is an object reference, we can also use it to call member properties and member methods. Of course, here is The super keyword can also call the constructor of the parent class.
specifically has the following usage :
1. Call the construction method of the parent class
Everyone should know about inheritance in Java. Subclasses inherit from the parent class. We can call the properties and methods of the parent class with the object of the subclass. We know that the properties and methods can only be called by the object. Then we can boldly assume: When creating the subclass object, it also creates the parent class object. The creation of the object is achieved by calling the constructor. Then when we create the subclass object, we should call the parent class's construction method.
Let's look at this code below:
public class Teacher {
public Teacher(){
System.out.println("我是一名人民教师。");
}
}
class Student extends Teacher {
public Student(){
System.out.println("我是一名学生。");
}
}
Below we create objects of subclasses:
public static void main(String[] args) {
Student s = new Student();
}
Output result:
我是一名人民教师。
我是一名学生。
Process finished with exit code 0
Through the printing results, we can see that when we create the subclass object, we first call the construction method of the parent class, and then call the construction method of the subclass. That is to say, when creating the subclass object, the parent class object is first created, and The previous conjectures are the same.
So the question is again: when is the parent class constructor called?
You can refer to the official Java documentation: https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#d5e14278
The English translation in the red box is: If the declared class is the primitive class Object, then the default constructor has an empty body. Otherwise, the default constructor simply calls the superclass constructor with no parameters.
In other words: Except that the constructor of the top class Object.class does not call the constructor of the parent class, all other classes call the constructor of the parent class by default in the constructor (the child class of the parent class is not explicitly declared as its parent The class is Object).
So by what is called? We then look at the official document:
The meaning of the above is probably: super class constructor is called by the super keyword and starts with the super keyword.
So the above Student
class should actually be like this:
class Student extends Teacher {
public Student(){
super();//子类通过super调用父类的构造方法
System.out.println("我是一名学生。");
}
public static void main(String[] args) {
Student s = new Student();
}
}
By default, the subclass calls the parent class's no-parameter construction method through super(). If the parent class explicitly declares a parameter-free construction method without declaring a no-parameter construction method, instantiating the subclass will report an error.
The solution is to call the parameterized construction method of the parent class through the super keyword:
class Student extends Teacher {
public Student(){
super("小马");
System.out.println("我是一名学生。");
}
public static void main(String[] args) {
Student s = new Student();
}
}
2. Call the member properties of the parent class
public class Teacher {
public String name = "小马";
public Teacher() {
System.out.println("我是一名人民教师。");
}
}
class Student extends Teacher {
public Student() {
System.out.println("我是一名学生。");
}
public void fatherName() {
System.out.println("我的父类名字是:" + super.name);//调用父类的属性
}
public static void main(String[] args) {
Student student = new Student();
student.fatherName();
}
}
Output result:
我是一名人民教师。
我是一名学生。
我的父类名字是:小马
Process finished with exit code 0
3. Call the method of the parent class
public class Teacher {
public String name;
public Teacher() {
System.out.println("我是一名人民教师。");
}
public void setName(String name){
this.name = name;
}
}
class Student extends Teacher {
public Student() {
super();//调用父类的构造方法
System.out.println("我是一名学生。");
}
public void fatherName() {
super.setName("小军");//调用父类普通方法
System.out.println("我的父类名字是:" + super.name);//调用父类的属性
}
public static void main(String[] args) {
Student student = new Student();
student.fatherName();
}
}
Output result:
我是一名人民教师。
我是一名学生。
我的父类名字是:小军
Process finished with exit code 0
4. Do this and super appear in the same construction method?
Assume thatsuper()
inthis()
keyword 061088e1325603
First, super()
to instantiate the parent class once. Then call this()
, this()
method will call the construction method of the subclass, in the construction method of the subclass, the parent class will be instantiated again. That is to say, we instantiate the subclass once and instantiate the parent class twice, so obviously the compiler is not allowed.
In turn this()
in super()
is the same as before. Moreover, the compiler has a limitation this()
and super()
can only appear in the first line of the construction method. Put these two keywords together, there is always a keyword in the second line, and the compilation cannot pass. .
Similarities and differences between this and super
super (parameter): calls a certain constructor in the base class (it should be the first statement in the constructor).
this (parameter): calls another formed constructor in this class (should be the first statement in the constructor).
super
: It refers to the member in the direct parent class of the current object (used to access the member data or function in the hidden parent class in the direct parent class. When the base class and the derived class have the same member definition, such as:super. Variable name ,
super. Member letter data name (actual parameter).
this
: It represents the name of the current object (where ambiguity is likely to occur in the program, this should be used to indicate the current object; if the shape of the function participates in the same name as the member data in the class, then this should be used to indicate the name of the member variable) .- Call
super()
must be written in the first line of the subclass construction method, otherwise the compilation will not pass. The first statement of each subclass's construction method is implicitly callingsuper()
. If the parent class does not have this form of constructor, an error will be reported during compilation. super()
this()
. The difference is thatsuper()
calls the construction method of the parent class from the child class, andthis()
calls other methods in the same class.super()
andthis()
need to be placed in the first line of the construction method.- Although you can
this
, you cannot call two. this
andsuper
cannot appear in the same constructor at the same time, becausethis
will inevitably call other constructors, and other constructors will inevitably havesuper
statements, so if there are the same statements in the same constructor, it will be lost. The meaning of the statement, the compiler will not pass.this()
andsuper()
both refer to objects, so neither can be used in thestatic
environment. Including:static
variable,static
method,static statement block.
- Essentially,
this
is a pointer to this object, butsuper
is a Java keyword.
end
I am a code farmer who is being beaten and working hard to advance. If the article is helpful to you, remember to like and follow, thank you!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。