Feb 23, 2008

Method Overriding in JAVA :

There are methods with same name and definition in subclass and its super class. In this example there is a function called add() in both of the classes super and sub. When this function is called by object of the subclass. add() function of the subclass overrides, the function in super class. add() function of the subclass will be called and add() function of the super class will be hidden.

In this example there is a class called demo1, it has a function called add(). subclass of demo1 is demo2, it also has a function called add() with same definition. When add() function is called by the object of the subclass demo2. add() function of the subclass overrides add() function of demo1 class. This is known as method overriding.



// method overriding demo

class demo1 // super class
{
void add()
{
int a,b,c;
a=10;
b=20;
c=a+b;
System.out.println("output from demo1");
System.out.println(c);
}
}

class demo2 extends demo1 // sub class
{
void add()
{
int a,b,c;
a=10;
b=20;
c=a*b;
System.out.println("output from demo2");
System.out.println(c);
}
}


class methoddemo
{
public static void main(String[] args)
{
demo2 d1;
d1 = new demo2();
d1.add();
}
}

No comments:

Post a Comment

Infolinks In Text Ads

Total Pageviews

Powered by Blogger.

Dont Forget To Follow Us

Blog Archive