Overriding - Java


Poly morphisms are two types . Complie time and runtime.
compile time polymorphisam is already discussed in overloading methods.
runtime polymorphism is achived by method over riding. when the super class and sub classes are with the same name it is called overriding.

WRITE A PROGRAM ON OVER RIDING MEMBERS.

class Abc
{
int a;
public void put()
{
System.out.println(a);
}
}
class Xyz extends Abc
{
int a;
public void put()
{
System.out.println(a+super.a);
}
Xyz(int x,int y)
{
a=x;
super.a=y;
}
}
class Sample
{
public static void main(String args[])
{
Xyz x=new Xyz(10,20);
x.put();
}
}

WRITE A PROGRAM ON OVERRIDING METHODS FOR DYNAMIC DISPATCH.

class Abc
{
public void disp()
{
System.out.println("This is ABC");
}
}
class Xyz extends Abc
{
public void disp()
{
System.out.println("This is xyz");
}
}

class Pqr extends Xyz
{
public void disp()
{
System.out.println("This is pqr");
}
}
class Sample
{
public static void main(String args[])
{
Abc a=new Abc();
Xyz x=new Xyz();
Pqr p=new Pqr();
Abc s;
s=a;
s.disp();
s=x;
s.disp();
s=p;
s.disp();
}
}

PROGRAM TO FIND THE AREA OF TRIANGLE , RECTANGLE,  AREA OF CIRCLE USING RUNTIME POLUMORPHISM.

class Abc
{
int b,h;
Abc()
{
b=10;
h=20;
}
public void disp()
{
System.out.println("Area of rectangle"+(b*h));
}
}

class Xyz extends Abc
{
Xyz(int x,int y)
{
b=x;
h=y;
}
public void disp()
{
System.out.println("Area of triangle"+(b*h*1/2));
}
}
class Pqr extends Abc
{
Pqr(int x)
{
b=x;
}
public void disp()
{
System.out.println("Area of circle"+(3.14*b*b));
}
}
class Sample
{
public static void main(String args[])
{
Abc a=new Abc();
Xyz x=new Xyz(10,20);
Pqr r=new Pqr(10);
Abc s;
s=a;
s.disp();
s=x;
s.disp();
s=r;
s.disp();
}
}

 

For
Online Classes

Contact Us: 9885348743