super keyword in java


SUBMITTED BY: rahulranjanmca

DATE: Jan. 5, 2016, 6:09 p.m.

FORMAT: Text only

SIZE: 2.1 kB

HITS: 32530

  1. The super keyword in java is a reference variable that is used to refer immediate parent class object.
  2. Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super reference variable.
  3. Usage of java super Keyword
  4. super is used to refer immediate parent class instance variable.
  5. super() is used to invoke immediate parent class constructor.
  6. super is used to invoke immediate parent class method.
  7. 1) super is used to refer immediate parent class instance variable.
  8. Problem without super keyword
  9. class Vehicle{
  10. int speed=50;
  11. }
  12. class Bike3 extends Vehicle{
  13. int speed=100;
  14. void display(){
  15. System.out.println(speed);//will print speed of Bike
  16. }
  17. public static void main(String args[]){
  18. Bike3 b=new Bike3();
  19. b.display();
  20. }
  21. }
  22. Test it Now
  23. Output:100
  24. 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.
  25. Solution by super keyword
  26. //example of super keyword
  27. class Vehicle{
  28. int speed=50;
  29. }
  30. class Bike4 extends Vehicle{
  31. int speed=100;
  32. void display(){
  33. System.out.println(super.speed);//will print speed of Vehicle now
  34. }
  35. public static void main(String args[]){
  36. Bike4 b=new Bike4();
  37. b.display();
  38. }
  39. }
  40. Test it Now
  41. Output:50
  42. 2) super is used to invoke parent class constructor.
  43. The super keyword can also be used to invoke the parent class constructor as given below:
  44. class Vehicle{
  45. Vehicle(){System.out.println("Vehicle is created");}
  46. }
  47. class Bike5 extends Vehicle{
  48. Bike5(){
  49. super();//will invoke parent class constructor
  50. System.out.println("Bike is created");
  51. }
  52. public static void main(String args[]){
  53. Bike5 b=new Bike5();
  54. }
  55. }
  56. Test it Now
  57. Output:Vehicle is created
  58. Bike is created

comments powered by Disqus