Java4teachus

Thursday, August 01, 2019

Super Keyword at Method Level in java

Super Keyword at Method Level


Whenever we inherit the Base class method into Derived class, there is a possibility that base class method are similar to derived class method and JVM gets ambiguity problem. 

In order to differentiate between the base class methods and derived class methods, in the context of derived class and base class methods must be preceded by super keyword.

Syntax:
Syntax-of-super-keyword-at-method-level.jpeg
If we do not write super keyword before the base class method name then base class method name can be hidden in the content of derived class. that method will be considered by JVM as derived class method called by itself infinitely and recursive rest and gets run time error called as "Stack Over Flow Error".

Program: 1


class BaseClass

{
void display()
{
System.out.println("Java4");
}
}
class DerivedClass extends BaseClass
{
void display()
{
super.display();
System.out.println("Teachus");
}
}
class SuperEx
{
public static void main(String[] args) 
{
DerivedClass d= new DerivedClass();
d.display();
}
}
Output


Super at Method Overridden Level


We know that method overriding = Method heading is same + Method Body is different.    

The process of  pre-defining the  original method of  base class into various derived class for performing different operations  is called "Method Overriding". To applying the method overriding concept, we  need to use the inheritance principle. 

Program: 2

class Circle
{
void draw()
{
System.out.println("Draw Circle--main method");
}
}
class Rectangle extends Circle
{
void draw()
{
super.draw();
System.out.println("Draw Rectangle--Overriden method");
}
}
class Square extends Rectangle
{
void draw()
{
super.draw();
System.out.println("Draw Square -- Overiding Method");
}
}
class Shapes
{
public static void main(String[] args) 
{
Square s=new Sqaure();
s.draw();
}
}
Output:
====================
Draw Circle -- main method.
Draw Rectangle -- overridden method
Draw Square --  Overridden method
====================

1 comment:

  1. Wow, it’s a very good post. The information provided by you is really very good and helpful for me. Keep sharing good information. I bookmark your blog because I found very good information on your blog ??????
    Check out this

    ReplyDelete

Thanks for visiting my site..