Method Overriding & Super Keyword

 Method Overriding

  • Simply,method overriding is changing the body of a method that is coming from super class to a a sub class.
  • It occurs when the sub class has the same method as in the super class.
  • In the "inheritance" article we could see that a method in the super class can be accessed by the sub class.
  • But if the both classes have 2 methods with the same name?
  • What can we do?
  • In such instances,the method in the sub class overrides the method in the super class.That concept can be called as "Method Overriding in JAVA".
  • In overriding,the methods that are related to the object are executed always.
  • Let me explain it by using the following example.


  • When studying the above code,we can identify the class Student as the super class and the class Child as the sub class.
  • And also,the method learn() is included in both classes.
  • Here we have created an object called "baby" by using the sub class Child.
  • So when we call the method learn() by using the object "baby",the method inside the subclass is executed.
  • This happens because the method inside the subclass override the method in the super class.
  • So we can get the output as above.
  • This is how "Method Overriding" works.

Super Keyword

  • Super keyword is used to call the constructor of the super class from the sub class.
  • Super keyword always access the super class.
  • Method and variables in the super class can be accessed by the super keyword from the sub class.


  • In the above example,we can see the method exist() in the sub class overrides the method exist() in the super class.
  • When we create a new object from that sub class,it calls the method inside the subclass Human.
  • But when we use the super keyword inside the method exist() in the subclass,it directly access the constructor of the super class and the method inside the super class is called.
  • That's why we get the output as above.
  • Finally we can call the constructor of the super class from its subclass by using the super() keyword.

Comments

Popular posts from this blog

Variable and Method types in JAVA

Polymorphism

Casting