Overriding:
- Method overriding is a mechanism in which a subclass inherits the methods of the superclass and sometimes the subclass modifies the implementation of a method defined in the super class.
- That means if subclass (Derived class) has the same method as declared in the parent class (base class).
- Method overriding is used for runtime polymorphism.
Rules for Java Method Overriding:
- The method must have the same name as in the parent class
- The method must have the same parameter as in the parent class.
- There must be inherited.
- A static method cannot be overridden. It can be proved by runtime polymorphism.
Syntax:
class base_class_name
{
return_type method_name(parameter_list)
{
//Statement
}
}
class derived_class_name
{
base_class_method(parameter_list)
{
//Statement
}
}
Example program:
#include<iostream.h>
#include<conio.h>
class Shape {
public:
double a;
void area() {
cout<<"\n\tCalculating area of Rectangle,Circle,Triangle .........";
}
};
class Rectangle:public Shape {
public:
void area(float l,float w) {
cout<<"\n\nEnter length and width of rectangle : ";
cin>>l>>w;
a=l*w; //area=length*width;
cout<<"\nArea of rectangle : "<<a;
}
};
class Circle:public Shape {
public:
void area(float r) {
cout<<"\n\nEnter radius of circle : ";
cin>>r;
a=3.14*r*r; //area=3.14*radius*radius;
cout<<"\nArea of circle : "<<a;
}
};
void main()
{
clrscr();
Shape s;
s.area();
Rectangle r;
r.area(6,3);
Circle c;
c.area(3.2);
getch();
}
Output:
Method overloading:
- Overloading is a mechanism in which we can use many methods having the same function name but can pass the different numbers of parameters or different types of parameters.
Syntax:
class base_class_name
{
return_type method_name(parameter_list)
{
//Statement
}
return_type same_method_name(parameter_list)
{
//Statement
}
}
Example program:
#include<iostream.h>
#include<conio.h>
class Shape {
public:
double a;
void area() {
cout<<"\n\tCalculating area of Rectangle,Circle,Triangle .........";
}
};
class Rectangle: public Shape {
public:
void area() {
float l,w;
cout<<"\n\nEnter length and width of rectangle : ";
cin>>l>>w;
a=l*w; //area=length*width;
cout<<"\nArea of rectangle : "<<a;
}
};
class Circle:public Shape {
public:
void area() {
float r;
cout<<"\n\nEnter radius of circle : ";
cin>>r;
a=3.14*r*r; //area=3.14*radius*radius;
cout<<"\nArea of circle : "<<a;
}
};
void main()
{
clrscr();
Shape s;
s.area();
Rectangle r;
r.area();
Circle c;
c.area();
getch();
}
Output:
No comments:
Post a Comment