Program to implement Method Overriding for following inheritance
When a superclass and subclass both have a method having same name and same type signatures (same return type and number of arguments with same data types) then the method in the subclass is said to be override the method of superclass.
In this program area( ) is a method of superclass Shape which have same method name, same return type and no arguments is overridden in subclasses Rectangle and Triangle. When a overridden method is called from within a subclass then it always calls the method in subclass, whereas the method defined in superclass will be hidden.
PROGRAM
In this program area( ) is a method of superclass Shape which have same method name, same return type and no arguments is overridden in subclasses Rectangle and Triangle. When a overridden method is called from within a subclass then it always calls the method in subclass, whereas the method defined in superclass will be hidden.
An abstract class is a class that cannot be instantiated. When a method is declared as "abstract" in a class it must be overridden by the subclass of the super classes which contain that method. An abstract method does not have body. Body of an abstract method will be defined by subclass. To declare an abstract method use the following form:
abstract return-type <method-name> (parameter-list);
Any class that contains one or more abstract methods must also be declared as abstract. That is, an abstract class cannot be directly instantiated with the new operator.
abstract class <class-name> {
// abstract method
abstract return-type <method-name>( );
// concrete or non-abstract method
return-type <method-name>( );
}
PROGRAM
import java.lang.*;
import java.io.*;
abstract class Shape {
int dim1,dim2;
void getd()throws IOException {
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
System.out.println ("Enter Value of 1st Dimension");
dim1=Integer.parseInt(br.readLine());
System.out.println ("Enter Value of 2nd Dimension");
dim2=Integer.parseInt(br.readLine());
}
abstract void area();
}
class Rectangle extends Shape {
void getd() throws IOException {
super.getd();
}
void area() {
int a=dim1*dim2;
System.out.println ("Area of Rectangle = "+a);
}
}
class Triangle extends Shape
{
void getd() throws IOException {
super.getd();
}
void area() {
double b=(1*dim1*dim2)/2;
System.out.println ("Area of Triangle = "+b);
}
}
public class MethodOverriding {
public static void main(String[] args) throws IOException {
Rectangle R = new Rectangle();
R.getd();
R.area();
Triangle T = new Triangle();
T.getd();
T.area();
}
}
OUTPUT
C:\>javac MethodOverriding.java C:\>java MethodOverriding Enter Value of 1st Dimension 42 Enter Value of 2nd Dimension 12 Area of Rectangle = 504 Enter Value of 1st Dimension 23 Enter Value of 2nd Dimension 52 Area of Triangle = 598.0