Super In Java

Super In Java :

Super In Java
  • Every object contains the instance variables of its class. What isn’t so obvious is that every object also has all the instance variables of all super classes (parent class, grandparent class, etc). These super class variables must be initialized before the class’s instances variables.
  • super keyword to call methods in a base class when you override methods in a subclass.

For example:

subclass that overrides a method inherited from the base class. The overridden method can call the method in the base class and modify the return value as shown in SubClass.java above.

  • private methods of the super-class cannot be called. Only public and protected methods can be called by the super keyword.
  • super keyword in java is a reference variable that is used to refer parent class objects.
  • Super keyword are not used in static Method.
  • Java 1.5 and later, the “super” keyword is also used to specify a lower bound on a wildcard type parameter in Generics.
public void sort(Comparator<? super T> comp) {
  ...
}
  • Super keyword restrictions
  • super refers to the immediate base class and its inherited members. It cannot be used to access private members in the class.
  • super is a keyword, not a real object. super cannot be assigned to a variable, passed to functions, or used in an Is comparison.
  • The method that super qualifies does not have to be defined in the immediate base class; it may instead be defined in an indirectly inherited base class. In order for a reference qualified by super to compile correctly, some base class must contain a method matching the name and the parameters in the call.
  • You cannot use super to call an abstract base class methods (This is no brainer).
  • super cannot be used to qualify itself. Therefore, the following code is not valid: super.super.doSomething();
  • MyBase cannot be used to access base class members that are marked as private.
  • super keyword used to access the members of the super class object.
  • It is used to store super class non static members memory reference through current sub class object for separating super class members from subclass members.
  • What are usage of java super Keyword?
  • Instance variable: super keyword is used to refer instance variables of immediate parent class
  • Super constructor: super() constructor call; is used to invoke constructor of immediate parent class
  • Overridden Method:<methodName>is used to invoke instance method of immediate parent class (when it is overridden in the sub-class)
  • super keyword cannot be used to refer in static context.
  • You can’t use super and this keywords in a static method and in a static initialization block even though you are referring static members.
class SuperClassOne {
inti;      //Non-Static member

    static void methodOne() {
        //static method
System.out.println("From Super Class");
    }
}

class SubClassOne extends SuperClassOne {

    static {
System.out.println(super.i);
this.methodTwo();

        //Above statements give compile time error
        //You can't use super and this keywords inside SIB
    }

    static void methodTwo() {
super.methodOne();
this.methodOne();

        //These also give compile time error
        //You can't use super and this keywords inside static method
        //even though you are accessing static methods
    }
}
  • You should call super() and this() calling statements inside the constructors only and they must be first statement in the constructors.
class SuperClassOne {

    void methodOne() {
System.out.println("From Super Class");
    }
}

class SubClassOne extends SuperClassOne {

    public SubClassOne() {
System.out.println("constructors");
        super();
        //compile time error
        //super() calling statement must be first statement in constructor
    }

    void methodTwo() {
        super();
        this();
        //compile time error
        //you should call super() and this()
        //calling statements only in constructors.
    }
}
  • super with variables
  • Derived class and base class has same data members. In that case there is a possibility of ambiguity for the JVM.
  • super variable refers immediate parent class instance.
  • super variable can invoke immediate parent class method.
  • super() acts as immediate parent class constructor and should be first line in child class constructor.
class Vehicle {
int speed = 120;
}

/* sub class Car extending vehicle */
class Car extends Vehicle {

int speed = 180;

    void display() {
        /* print speed of base class (vehicle) */
System.out.println("Speed: " + super.speed);
        //System.out.println("Speed: " + speed);
    }
}

/* Driver program to test */
class Test {

    public static void main(String[] args) {
        Car small = new Car();
small.display();
    }
}
/*
Output
Speed: 120
*/
public class Car {
int speed = 100;
}

class FastCar extends Car {
int speed = 200;

FastCar(int a, int b) {
super.speed = 100;
        speed = b;
    }
}
  • super with methodsoverriding
  • When we want to call parent class method.Parent and child class have same named methods then to resolve ambiguity we use super keyword.
class Person {
    void message() {
System.out.println("This is person class");
    }
}

/* Subclass Student */
class Student extends Person {
    @Override
    void message() {
System.out.println("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();
    }
}

/*
Output 
Student class
This is person class
*/
  • super with constructors
  • Access the parent class constructor. One more important thing is that, ‘’super’ can call both parametric as well as non parametric constructors depending upon the situation.
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 student = new Student();
    }
}

/*
Output 
Person class Constructor
Student class Constructor
*/
  • A subclass can have its own private data members, so a subclass can also have its own constructors.
  • The constructors of the subclass can initialize only the instance variables of the subclass. Thus, when a subclass object is instantiated the subclass object must also automatically execute one of the constructors of the superclass.
  • To call a superclass constructor the super keyword is used.
Rectangle.java

public class Rectangle
{
   private double length;  // To hold length of rectangle
   private double width;  // To hold width of rectangle

   public Rectangle()
   {
      length = 0;
      width = 0;
   }

   public Rectangle(double length, double width)
   {
this.length = length;
this.width = width;
   }

   public double getArea()
   {
      return length * width;
   }
}

Box.java
public class Box extends Rectangle
{
   private double height;  // To hold height of the box

   /**
    *  The constructor initialize box's 
*  length, width and height with default value.  
    */

   public Box()
   {
      // Call the superclass default constructor to initialize length and width.
      super();
      //Initialize height.
      height = 0;
   }

    public Box(double length, double width, double height)
    {
      // Call the superclass constructor to initialize length and width.
      super(length, width);

      // Initialize height.
this.height = height;
   }

   public double getVolume()
   {
      return getArea() * height;
   }
}

BoxApp.java
public class BoxApp {
    public static void main(String[] args)
   {
      // Create a box object.
      Box myBox1 = new Box();

      // Display the volume of myBox1.
System.out.println("Volume: " + myBox1.getVolume());

      // Create a box object.
      Box myBox2 = new Box(12.2, 3.5, 2.0);

      // Display the volume of myBox2.
System.out.println("Volume: " + myBox1.getVolume());
   }
}

/*
Output
Volume: 0.0
Volume: 0.0
*/
  • Parameterized super() call to invoke parameterized constructor of parent class (Explicit call to superclass constructor)
  • When we have a constructor in parent class that takes arguments then we can use parameterized super.
class Parentclass {
    //no-arg constructor
Parentclass() {
System.out.println("no-arg constructor of parent class");
    }

    //arg or parameterized constructor
Parentclass(String str) {
System.out.println("parameterized constructor of parent class");
    }
}

class Subclass extends Parentclass {

    Subclass() {
        /* super() must be added to the first statement of constructor 
	* otherwise you will get a compilation error. Another important 
	* point to note is that when we explicitly use super in constructor
	* the compiler doesn't invoke the parent constructor automatically.
         */
        super("Hahaha");
System.out.println("Constructor of child class");
    }

    void display() {
System.out.println("Hello");
    }

    public static void main(String args[]) {
        Subclass obj = new Subclass();
obj.display();
    }
}

/*
output
parameterized constructor of parent class
Constructor of child class
Hello
*/
  • What if the child class is not overriding any method: No need of super
  • When child class doesn’t override the parent class method then we don’t need to use the super keyword to call the parent class method. This is because in this case we have only one version of each method and child class has access to the parent class methods so we can directly call the methods of parent class without using super.
class Parentclass {
    void display() {
System.out.println("Parent class method");
    }
}

class Subclass extends Parentclass {

    void printMsg() {
        /* This would call method of parent class,
	 * no need to use super keyword because no other
	 * method with the same name is present in this class
        */
        display();
    }

    public static void main(String args[]) {

        Subclass obj = new Subclass();
obj.printMsg();
    }
}

/*
Output 
Parent class method
*/

Real use super

class Person {
int id;
    String name;

    Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

class Emp extends Person {
    float salary;
Emp(int id, String name, float salary) {
        super(id, name); //reusing parent constructor  
this.salary = salary;
    }

    void display() {
System.out.println(id + " " + name + " " + salary);
    }
}

class Test {
    public static void main(String[] args) {
Emp e1 = new Emp(1, "kamlesh", 45000f);
        e1.display();
    }
}

/*
Output 
1 kamlesh 45000.0
*/

Question :

  • What will happen if we are calling super() in constructor but our class does not extending any class?
  • If our class not extending any class Yes still we can use super(); call in our class
  • Because in java every class will extend Object class by default this will be added by JVM.
  • But make sure we are using only super(); default call we cannot place parameterized super call because Object class does not have any parameterized constructor.
public Class Box{
	Sample(){
	super();
	System.out.println("Sample class constructor called "); 
}
  • Can we call super class methods from static methods of sub class?
  • No we cannot use super in static methods of sub class because super belongs to object level so we cannot use super in static methods.
  • If we try to use in sub class static methods compile time error will come.
public class Super {
int x, y;

public void add() {
System.out.println("Super class");
    }

public class Sub extends Super {
public void add() {
            //super.x = 10;
System.out.println("Super class add method");
        }
    }

public static void main(String[] args) {
Super.x = 10;
Super.y = 20;
    }
}
  • Difference Between this() and super() ?
  • Super keyword is always pointing to base class features and this keyword is always pointing to current class features.
  • Establishing the communication between base class and derived class constructor.Establishing the communication between current class constructors.
  • It can be used to only inside child class constructor. It can be used inside another constructor of same class.
  • In a case where there are no instance variables what does the default constructor initialize?
  • superclass ( Object Class ) constructor to be called while creation of any object. So super constructor is called in case there are no instance variables to initialize.
  • Whether it is possible to refer static variable of parent class from child class using super keyword?
  • It is very possible to access parent class’s static variable using super keyword.
  • But its usage is discouraged with compiler warning with message “The static field <parent-class-name>.<static-variable-name> should be accessed in a static way”.
  • As it can be accessed using class-name.

Syntax :

<class-name>.<static-variable-name>
classParentClass {
    String siteName = "www.fluttertutorial.in";
staticintsiteSearch = 17000;
}

public class ChildClass extends ParentClass {
    String siteName = "oracle.com";

public void display() {
System.out.println("Site search " + super.siteSearch);
    }

public static void main(String[] args)
    {
ChildClassobj = new ChildClass();
obj.display();

System.out.println("Site name " + obj.siteName);
    }
}

/*
Output
Site search 17000
Site name oracle.com
*/

6) Can we use super keyword in static method of a sub class for calling parent class method?

  • No, we cannot use super keyword in static methods because it belongs to the immediate parent object and static belongs to the class level.

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in