java中关键字super

super关键字的作用

java中的super关键字是一个引用变量,用于引用父类对象。关键字“super”以继承的概念出现在类中。

主要用于以下情况:1.调用父类的方法   2.调用父类的变量  3.调用父类的构造方法

1.调用父类的方法

当我们要调用父类方法时使用。父类和子类都具有相同的命名方法,那么为了解决歧义,我们使用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

2.调用父类的变量

当子类和父类具有相同的数据成员时,会发生此情况。在这种情况下,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

3.调用父类的构造方法

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()必须是子类构造函数中的第一条语句。

猜你喜欢

转载自www.cnblogs.com/z-cg/p/12242507.html