
本文共 2370 字,大约阅读时间需要 7 分钟。
this关键字:
In Java, the keyword "this" refers to the current object instance and is used extensively in constructors. It is subject to the "lexically nearest" rule, which means it refers to the variable in the nearest scope.
1. **Constructor Calls**: When a constructor is called with parameters, "this(...)" is used to invoke another constructor of the same class.
2. **Method Invocation**: When "this.method()" is used in a constructor, it refers to an instance method, not a constructor.
3. **Legacy Constructor Calls**: In earlier Java versions, calling a constructor from another constructor requires explicitly using "this(...)" to prevent compiler ambiguity.
4. **Placement**: The "this" keyword must be placed at the beginning of a constructor.
```javaclass Student { String name; // 姓名 int age; // 年龄 char sex; // 性别 String id; // 学号 // No-argument constructor Student() {} // Constructor with three parameters Student(String name, int age, char sex) { this.name = name; this.age = age; this.sex = sex; } // Constructor with two parameters Student(String name, String id) { this(name, id); // this.age = age; 这里没有,因为父类没有对应的参数 // 可能还需要添加其他初始化语句 } // Constructor with four parameters Student(String name, int age, char sex, String id) { // 调用另一个有两个参数的构造方法 this(name, id); this.age = age; this.sex = sex; }}
super关键字:
用于继承关系中的子类操作。这一关键字在没有被明确调用时,会默认调用父类的空构造函数。以下是一些注意事项:
1. 子类无需显式调用super(),编译器会自动加上。
2. super()用于创建父类对象的必需。
3. 如果父类有参数化构造,子类构造必须通过super(...)来指定参数。
4. super必须位于子类构造函数的首行。
class Rectangle { private int length; // 长 private int width; // 宽 // 无参数构造 Rectangle() {} // 有参数构造 Rectangle(int length, int width) { if (length > 0) { this.length = length; } if (width > 0) { this.width = width; } } public int perimeter() { // 周长计算 return 2 * (length + width); } public int area() { // 面积计算 return length * width; }}// 子类继承Rectangleclass RectangleDecorator extends Rectangle { private int length; // 父类的构造必须通过super()调用 RectangleDecorator(int length) { super(length, length); // 调用父类的有两个参数的构造 }}
在实际编写代码时,需要根据具体情况灵活运用"this"和"super"关键字,以强调构造对象的正确性和复杂度。
```发表评论
最新留言
关于作者
