Tuesday, 1 November 2016

SUPER KEYWORD IN JAVA

Tags

Usage of java super Keyword
  1. super is used to refer  parent class instance variable.        in 1st example
  2. super() is used to invoke parent class constructor.      using super(); in 2nd example
  3. super is used to invoke parent class method. using super.methodname();in 2nd example.

1st example

class Vehicle{                                     
int speed = 50;

class bike extends vehicle{
int speed  = 100;
void display(){
System.out.println(super.speed);// it will print speed of vehicle
}
}

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

}

OUTPUT :
50

2nd example

public class base {

base(){
System.out.println("constructor of base !");
}

void eat(){
System.out.println(" base is eating !");
}

}

--

public class der extends base {

der(){
super(); // super(); call constructor of base class
System.out.println("constructor of derieved ");
}
void eat(){
super.eat();// super.methodname call method of base class//
System.out.println(" 2nd  derieved is eating !");
}
public static void main(String[] args) {
der d1 = new der();
d1.eat();
}
}

OUTPUT :




Enter Your Comments Below Emoticon