- By using super keyword we can access super class variables and super class methods in sub class.
- "Super" always refers to super class object.
- One more interesting point about super is we can call super call constructors from sub class constructor using super keyword.
- By default in sub class constructor super() call will be added by jvm.
- We can also explicitly mention super call but rule is super() call must be first statement of the sub class constructor.
- Let us see how sub class constructor calls super class constructors automatically.
Java example program to demonstrate super call execution from sub class constructor to super class constructor
- package com.superkeywordinjava;
- public Class SuperDemo{
- SuperDemo(){
- System.out.println("Inside super class constructor");
- }
- }
- package com.superkeywordinjava;
- public Class Subdemo extends SuperDemo{
- Subdemo(){
- System.out.println("Inside sub class constructor");
- }
- public static void main (String args[]) {
- Subdemo obj= new Subdemo();
- }
- }
Output:
- Inside super class constructor
- Inside sub class constructor
- In the above programs whenever we are creating object of the sub class corresponding sub class constructor will be executed
- By default in sub class constructor super(); call will be added so now it will call super class zero argument constructor.
- Subdemo(){
- super(); // will be added automatically
- System.out.println("Inside sub class constructor");
- }
- Whenever there is no constructor in sub class then default constructor added automatically and that contains super call in it.
- And also when ever we define a constructor in our class .By default super(); call will be added automatically as first statement.
- package com.superkeywordinjava;
- public Class SuperDemo{
- SuperDemo(){
- System.out.println("Inside super class constructor");
- }
- }
- package com.superkeywordinjava;
- public Class Subdemo extends SuperDemo{
- Subdemo(){
- super();
- System.out.println("Inside sub class constructor");
- }
- public static void main (String args[]) {
- Subdemo obj= new Subdemo();
- }
- }
Output:
- Inside super class constructor
- Inside sub class constructor
- Super call must be first statement inside the sub class constructor otherwise compile time error will come.
- If super class having parameterized constructor it is mandatory to call super class constructor explicitly by passing required parameters.
- other wise compile time error will come
- Sub(){
- super(1,2); // will work fine
- System.out.println("Inside sub class constructor");
- }
No comments