📜  Javasuper 和 super() 的区别示例

📅  最后修改于: 2021-09-11 04:02:53             🧑  作者: Mango

极好的

Java的super关键字是一个引用变量,用于引用父类对象。关键字“super”带着继承的概念出现了。基本上,这种形式的super用于在超类中不存在构造函数时初始化超类变量。另一方面,它通常用于访问超类的特定变量。

// Java code to demonstrate super keyword
  
/* 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 关键字还可以通过在其后添加'()’ 来访问父类构造函数,即super()。更重要的一点是,“super()”可以根据情况调用参数和非参数构造函数。

// Java code to demonstrate 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 super()
The super keyword in Java is a reference variable that is used to refer parent class objects. The super() in Java is a reference variable that is used to refer parent class constructors.
super can be used to call parent class’ variables and methods. super() can be used to call parent class’ constructors only.
The variables and methods to be called through super keywordd can be done at any time, Call to super() must be first statement in Derived(Student) Class constructor.
If one does not explicitly invoke a superclass variables or methods, by using super keyword, then nothing happens If a constructor does not explicitly invoke a superclass constructor by using super(), the Java compiler automatically inserts a call to the no-argument constructor of the superclass.