Java中的超级关键字

这个 超级的 java中的关键字是一个引用变量,用于引用父类对象。关键词“super”是随着继承的概念出现的。它主要用于以下情况:

null

1.在变量中使用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

在上面的示例中,基类和子类都有一个成员maxSpeed。我们可以使用super关键字访问子类中基类的maxSpeed。

2.使用super with方法: 当我们想要调用父类方法时,就会用到这个方法。所以,每当父类和子类具有相同的命名方法时,我们就使用super关键字来解决歧义。这个代码片段有助于理解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

在上面的例子中,我们已经看到,如果我们只调用方法message(),那么就会调用当前的类message(),但是通过使用super关键字,也可以调用超类的message()。

3. . 与构造函数一起使用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”调用了超类构造函数。

其他要点:

  1. 对super()的调用必须是派生(学生)类构造函数中的第一条语句。
  2. 如果构造函数没有显式调用超类构造函数,Java编译器会自动插入对该超类的无参数构造函数的调用。如果超类没有无参数构造函数,则会出现编译时错误。对象 有这样一个构造函数,所以如果Object是唯一的超类,就没有问题了。
  3. 如果子类构造函数显式或隐式调用其超类的构造函数,您可能会认为整个构造函数链都在调用,一直返回到对象的构造函数。事实上就是这样。它叫 构造函数链 ..

本文由 维什瓦吉特·斯利瓦斯塔瓦 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享