Advertisement
Shailrshah

Super Keyword

Dec 17th, 2013
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. /*
  2. The super keyword is used in 3 cases:-
  3.     1. To refer instance variable of immediate parent class
  4.     2. To invoke custructor of immediate parent class
  5.     3. To invoke a method of immediate parent class
  6. */
  7. class SuperClass{
  8.     int a = 1; //instance variable of parent class
  9.     SuperClass(){
  10.         System.out.println("\nControl is in super class Constructor.");
  11.     }
  12.     void SuperClassMethod(){
  13.         System.out.println("\nControl is in super class Method.");
  14.     }
  15. }
  16. class SubClass extends SuperClass{
  17.     int a = 2; //instance variable of subclass
  18.     SubClass(){
  19.         super(); //To call the immediate parent's constructor
  20.         System.out.println("\nControl is in sub class Constructor.");
  21.     }
  22.     void SubClassMethod(){
  23.         System.out.println("\nControl is in sub class Method");
  24.         super.SuperClassMethod(); //To invoke a method of immediate parent class
  25.         System.out.println("\na(super class): "+super.a);//To refer to class variable of immediate paraent class
  26.         System.out.println("\na(sub class): "+a);
  27.     }
  28. }
  29. class SuperTest{
  30.     public static void main(String args[]){
  31.         new SubClass().SubClassMethod();
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement