Friday, 27 March 2015

super keyword in java

Super keyword in java


The super keyword in java is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.

Usage of java super Keyword

  1. super is used to refer immediate parent class instance variable.
  2. super() is used to invoke immediate parent class constructor.
  3. super is used to invoke immediate parent class method.

1) super is used to refer immediate parent class instance variable.

Problem without super keyword
  1. class Vehicle{  
  2.   int speed=50;  
  3. }  
  4. class Bike3 extends Vehicle{  
  5.   int speed=100;  
  6.   void display(){  
  7.    System.out.println(speed);//will print speed of Bike   
  8.   }  
  9.   public static void main(String args[]){  
  10.    Bike3 b=new Bike3();  
  11.    b.display();  
  12. }  
  13. }  
Output:100
In the above example Vehicle and Bike both class have a common property speed. Instance variable of current class is refered by instance bydefault, but I have to refer parent class instance variable that is why we use super keyword to distinguish between parent class instance variable and current class instance variable.

Solution by super keyword
  1. //example of super keyword  
  2.   
  3. class Vehicle{  
  4.   int speed=50;  
  5. }  
  6.   
  7. class Bike4 extends Vehicle{  
  8.   int speed=100;  
  9.       
  10.   void display(){  
  11.    System.out.println(super.speed);//will print speed of Vehicle now  
  12.   }  
  13.   public static void main(String args[]){  
  14.    Bike4 b=new Bike4();  
  15.    b.display();  
  16.      
  17. }  
  18. }  
Output:50

2) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor as given below:
  1. class Vehicle{  
  2.   Vehicle(){System.out.println("Vehicle is created");}  
  3. }  
  4.   
  5. class Bike5 extends Vehicle{  
  6.   Bike5(){  
  7.    super();//will invoke parent class constructor  
  8.    System.out.println("Bike is created");  
  9.   }  
  10.   public static void main(String args[]){  
  11.    Bike5 b=new Bike5();  
  12.         
  13. }  
  14. }  
Output:Vehicle is created
       Bike is created

Note: super() is added in each class constructor automatically by compiler.

java super
As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement.If you are creating your own constructor and you don't have either this() or super() as the first statement, compiler will provide super() as the first statement of the constructor.

Another example of super keyword where super() is provided by the compiler implicitly.

  1. class Vehicle{  
  2.   Vehicle(){System.out.println("Vehicle is created");}  
  3. }  
  4.   
  5. class Bike6 extends Vehicle{  
  6.   int speed;  
  7.   Bike6(int speed){  
  8.     this.speed=speed;  
  9.     System.out.println(speed);  
  10.   }  
  11.   public static void main(String args[]){  
  12.    Bike6 b=new Bike6(10);  
  13.  }  
  14. }  
Output:Vehicle is created
       10

3) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used in case subclass contains the same method as parent class as in the example given below:
  1. class Person{  
  2. void message(){System.out.println("welcome");}  
  3. }  
  4.   
  5. class Student16 extends Person{  
  6. void message(){System.out.println("welcome to java");}  
  7.   
  8. void display(){  
  9. message();//will invoke current class message() method  
  10. super.message();//will invoke parent class message() method  
  11. }  
  12.   
  13. public static void main(String args[]){  
  14. Student16 s=new Student16();  
  15. s.display();  
  16. }  
  17. }  
Output:welcome to java
       welcome
In the above example Student and Person both classes have message() method if we call message() method from Student class, it will call the message() method of Student class not of Person class because priority is given to local.

In case there is no method in subclass as parent, there is no need to use super. In the example given below message() method is invoked from Student class but Student class does not have message() method, so you can directly call message() method.

Program in case super is not required

  1. class Person{  
  2. void message(){System.out.println("welcome");}  
  3. }  
  4.   
  5. class Student17 extends Person{  
  6.   
  7. void display(){  
  8. message();//will invoke parent class message() method  
  9. }  
  10.   
  11. public static void main(String args[]){  
  12. Student17 s=new Student17();  
  13. s.display();  
  14. }  
  15. }  
Output:welcome

Covariant Return Type

Covariant Return Type

The covariant return type specifies that the return type may vary in the same direction as the subclass.
Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it changes its return type to subclass type. Let's take a simple example:

Note: If you are beginner to java, skip this topic and return to it after OOPs concepts.


Simple example of Covariant Return Type

  1. class A{  
  2. A get(){return this;}  
  3. }  
  4.   
  5. class B1 extends A{  
  6. B1 get(){return this;}  
  7. void message(){System.out.println("welcome to covariant return type");}  
  8.   
  9. public static void main(String args[]){  
  10. new B1().get().message();  
  11. }  
  12. }  
Output:welcome to covariant return type
As you can see in the above example, the return type of the get() method of A class is A but the return type of the get() method of B class is B. Both methods have different return type but it is method overriding. This is known as covariant return type.

More topics on Method Overriding (Not For Beginners)

More topics on Method Overriding (Not For Beginners)

There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
  1. private
  2. default
  3. protected
  4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers.

1) private access modifier

The private access modifier is accessible only within class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so there is compile time error.
  1. class A{  
  2. private int data=40;  
  3. private void msg(){System.out.println("Hello java");}  
  4. }  
  5.   
  6. public class Simple{  
  7.  public static void main(String args[]){  
  8.    A obj=new A();  
  9.    System.out.println(obj.data);//Compile Time Error  
  10.    obj.msg();//Compile Time Error  
  11.    }  
  12. }  

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:
  1. class A{  
  2. private A(){}//private constructor  
  3. void msg(){System.out.println("Hello java");}  
  4. }  
  5. public class Simple{  
  6.  public static void main(String args[]){  
  7.    A obj=new A();//Compile Time Error  
  8.  }  
  9. }  

Note: A class cannot be private or protected except nested class.


2) default access modifier

If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package.
  1. //save by A.java  
  2. package pack;  
  3. class A{  
  4.   void msg(){System.out.println("Hello");}  
  5. }  
  1. //save by B.java  
  2. package mypack;  
  3. import pack.*;  
  4. class B{  
  5.   public static void main(String args[]){  
  6.    A obj = new A();//Compile Time Error  
  7.    obj.msg();//Compile Time Error  
  8.   }  
  9. }  
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.

3) protected access modifier

The protected access modifier is accessible within package and outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.
  1. //save by A.java  
  2. package pack;  
  3. public class A{  
  4. protected void msg(){System.out.println("Hello");}  
  5. }  
  1. //save by B.java  
  2. package mypack;  
  3. import pack.*;  
  4.   
  5. class B extends A{  
  6.   public static void main(String args[]){  
  7.    B obj = new B();  
  8.    obj.msg();  
  9.   }  
  10. }  
Output:Hello

4) public access modifier

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example of public access modifier

  1. //save by A.java  
  2.   
  3. package pack;  
  4. public class A{  
  5. public void msg(){System.out.println("Hello");}  
  6. }  
  1. //save by B.java  
  2.   
  3. package mypack;  
  4. import pack.*;  
  5.   
  6. class B{  
  7.   public static void main(String args[]){  
  8.    A obj = new A();  
  9.    obj.msg();  
  10.   }  
  11. }  
Output:Hello

Understanding all java access modifiers

Let's understand the access modifiers by a simple table.
Access Modifierwithin classwithin packageoutside package by subclass onlyoutside package
PrivateYNNN
DefaultYYNN
ProtectedYYYN
PublicYYYY

Java access modifiers with method overriding

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
  1. class A{  
  2. protected void msg(){System.out.println("Hello java");}  
  3. }  
  4.   
  5. public class Simple extends A{  
  6. void msg(){System.out.println("Hello java");}//C.T.Error  
  7.  public static void main(String args[]){  
  8.    Simple obj=new Simple();  
  9.    obj.msg();  
  10.    }  
  11. }  
The default modifier is more restrictive than protected. That is why there is compile time error.