What is the usage of Super Keyword – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 27 Dec 2020 17:05:47 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg What is the usage of Super Keyword – Programmerbay https://programmerbay.com 32 32 What are Three Uses of Super Keyword ? https://programmerbay.com/what-are-three-uses-of-super-keyword/ https://programmerbay.com/what-are-three-uses-of-super-keyword/#respond Tue, 11 Aug 2020 16:17:58 +0000 https://www.programmerbay.com/?p=4526 What is Super keyword ?
  1. In the Inheritance concept, when a subclass object calls its instance member function which can consist of implicit reference variables this or super.
  2. The difference between this and super is that this reference variable is of subclass type, whereas super reference variable is of superclass type.
  3. Call to super is made first prior to the constructor of the subclass. In other words, the constructor of the parent class always executes before the child class constructor.
  4. If the subclass constructor does not explicitly invoke its superclass constructor then the compiler automatically puts the super statement in the constructor of the subclass.

What are the Three Uses of Super Keyword ?

  • If a child class overrides one of its parent class’s methods, you can invoke that overridden method through the use of the keyword super. In other words, Whenever there is a method having the same name in both parent and child class. You can invoke the method of a parent class by putting the super keyword in front of the name of the overridden method which would refer to the parent’s class method.
  • Super keyword helps in resolving the name conflict between member variables of superclass and subclass having the same name.
  • Passing values through constructor while creating an object of the subclass, it is also essential to provide values to superclass variables too. For this, we can call super to pass the values to the superclass constructor.

Java program to show the usage of Super keyword

Program:

class A
{
  int z;
    A (int a)
  {
    z = a;
  } public void f1 ()
  {
  }

}

class B extends A
{
  int z;
    B (int a, int b)
  {
    super (a);    //call for super class constructor
    z = b;
  } public void f1 ()
  {
    super.f1 ();    //call for super class method } 
    public void f2 ()
    {
      super.z = 4;   //call for super class variable 
  }
      
  } 
  public class Example
  {
    public static void main (String[]args)
    {
      B obj = new B ();
      B obj = new B (5, 3);
        obj.f1 ();
        obj.f2 ();
  }
      
  }

 

]]>
https://programmerbay.com/what-are-three-uses-of-super-keyword/feed/ 0