您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,super
关键字是一个引用变量,它指向当前对象直接父类的一个实例。使用super
关键字可以访问父类的成员变量、方法和构造函数。以下是一些使用super
关键字的技巧:
当子类和父类有同名的成员变量时,可以使用super
关键字来访问父类的成员变量。
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void print() {
System.out.println("Parent's x: " + super.x); // 输出: Parent's x: 10
System.out.println("Child's x: " + this.x); // 输出: Child's x: 20
}
}
当子类重写了父类的方法时,可以使用super
关键字来调用父类的方法。
class Parent {
void display() {
System.out.println("Parent's display method");
}
}
class Child extends Parent {
@Override
void display() {
super.display(); // 调用父类的display方法
System.out.println("Child's display method");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.display();
// 输出:
// Parent's display method
// Child's display method
}
}
在子类的构造函数中,可以使用super
关键字来调用父类的构造函数。这通常用于初始化继承自父类的成员变量。
class Parent {
int x;
Parent(int x) {
this.x = x;
}
}
class Child extends Parent {
int y;
Child(int x, int y) {
super(x); // 调用父类的构造函数
this.y = y;
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child(10, 20);
System.out.println("Parent's x: " + child.x); // 输出: Parent's x: 10
System.out.println("Child's y: " + child.y); // 输出: Child's y: 20
}
}
当子类和父类有同名的方法或变量时,使用super
关键字可以明确地指定要访问的是父类的成员。
class Parent {
int value = 100;
void setValue(int value) {
this.value = value;
}
int getValue() {
return value;
}
}
class Child extends Parent {
int value = 200;
void setValue(int value) {
super.value = value; // 设置父类的value
}
int getValue() {
return super.getValue(); // 获取父类的value
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.setValue(300);
System.out.println("Parent's value: " + child.getValue()); // 输出: Parent's value: 300
}
}
虽然不能直接访问父类的私有成员,但可以通过父类提供的公共或受保护的方法来访问。
class Parent {
private int privateValue = 100;
protected int accessPrivateValue() {
return privateValue;
}
}
class Child extends Parent {
void printPrivateValue() {
System.out.println("Parent's private value: " + accessPrivateValue()); // 通过方法访问
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.printPrivateValue(); // 输出: Parent's private value: 100
}
}
使用super
关键字可以有效地管理和访问继承关系中的成员,避免命名冲突,并确保代码的可读性和可维护性。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。