Java Interview Question

Use this intermediate question and answer to prepare for your next Java interview.

What is super? Are the following uses of super correct?

class A {
  public A(int x) { }

class B extends A {
  int y;
  public B() {
    y = 5;

The super keyword is used to reference the parent class and methods of the parent class. super can be used to invoke the constructor of the parent class as well. In this case, it must be the first line of code. If there is no default constructor in the base class, then it is mandatory to call one of the base class parameterized constructors.

As mentioned above, super must be the first line of code in the sample. Also, the variable y cannot be used in the call to super, because the object of B has not yet been instantiated.

Looking for developers?