Super Keyword


Super Keyword

“Super” keyword is used to call the parent class’s methods in Java, or it refers to the object of the parent class. Super keyword to used to access the parent class constructor in the main method.

The “Super” keyword is specifically used to eliminate the confusion between superclass and subclass in which the names of the methods are the same. It is used to invoke the immediate parent class method or instance variable.
The super keyword is used with the concept of Inheritance.

The Super keyword is used when the child class has the same variable name as the parent class. Thus, to invoke the parent class, we can write a super keyword before the same variable name to call the parent class variable.
Similarly, suppose we have an identical name method in the parent class and the child class, using the super keyword before the method, the immediate parent class method will be invoked.
In order to call the parent class method while having the same name in its child class, we need to use the “super” keyword before the method name.

The “Super” keyword is used to invoke the parent class directly by only writing the “super().”

Note:- If we do not add the Super keyword in the child class, the compiler will automatically create the super() constructor for each class and adds super() as the first statement of the default constructor.

                class Fruit{

                    }
	                   |
	            Compiler addition 
		               |
                class Mango{
                Fruit(){
                super(); //first statement
                }
            }

Note:- super keyword represents the current instance of the parent class.

Example:

Com.knowledge2life public class Main { protected String brand = "Net programing"; public void inheritance() { System.out.println("Knowledge2life1, Knowledge2life2!"); } } class Website1 extends Main { private String Webname = "Knowledge2life3"; public static void main(String[] args) { Website1 web = new Website1(); web.inheritance(); System.out.println(web.brand + " " + web.Webname); } }

OUTPUT:

Knowledge2life1, Knowledge2life2!
Net programming Knowledge2life3