以下是 Java 中Super关键字的各种用法:
- 使用 super 和变量
当派生类和基类具有相同的数据成员时,就会出现这种情况。在这种情况下,JVM 可能会产生歧义。
/* Base class vehicle */
class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
/* Driver program to test */
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
输出:
Maximum Speed: 120
- 使用 super with 方法
这在我们要调用父类方法时使用。因此,每当父类和子类具有相同的命名方法时,为了解决歧义,我们使用 super 关键字。
/* Base class Person */
class Person
{
void message()
{
System.out.println("This is person class");
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
/* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
输出:
This is student class
This is person class
- 在构造函数中使用 super
super 关键字也可以用来访问父类的构造函数。更重要的一点是,“super”可以根据情况调用参数构造函数和非参数构造函数。
/* superclass Person */
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
/* subclass Student extending the Person class */
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
/* Driver program to test*/
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
输出:
Person class Constructor
Student class Constructor
由于super()会调用父类的构造函数,所以它应该是子类构造函数中要执行的第一条语句。如果要调用父类的方法,请使用super而不是super()。
有关更多信息,请阅读:Java 中的超级