Written by Sai Sandeep Thota on November 6, 2013 in Java > Programming

Java Program to calculate Area using Abstract Class and Methods

GET ALERTS:

Get our Latest updates delivered to your mailbox!

In this tutorial we will be learning how to define a abstract class and methods. Placing a abstract keyword before the class name defines the class as abstract. Same follows for methods also. If we place abstract keyword before a method, we cannot define body of the method.

So we need to inherit the abstract class and define the abstract methods in the new class. Coming to the program in this tutorial we are calculating Area of Triangle, Rectangle, Square and Circle. We have defined an abstract class called calcArea and defined four abstract methods in it each having one or more parameters.

findArea class inherits calcArea class and the body of methods are defined here. We are using area class for declaring object of findArea class. We cannot create object for an abstract class. We can declare body of a non-abstract method in an abstract class but we need to call the method using a method in a non-abstract class.

Java Program to calculate Area using Abstract Class and Methods

import java.util.Scanner;

abstract class calcArea {
	abstract void findTriangle(double b, double h);
	abstract void findRectangle(double l, double b);
	abstract void findSquare(double s);
	abstract void findCircle(double r);
}

class findArea extends calcArea {

	void findTriangle(double b, double h)
	{
		double area = (b*h)/2;
		System.out.println("Area of Triangle: "+area);
	}

	void findRectangle(double l, double b)
	{
		double area = l*b;
		System.out.println("Area of Rectangle: "+area);
	}
	
	void findSquare(double s)
	{
		double area = s*s;
		System.out.println("Area of Square: "+area);
	}
	
	void findCircle(double r)
	{
		double area = 3.14*r*r;
		System.out.println("Area of Circle: "+area);
	}
}
		
class area {
	public static void main(String args[])
	{
		double l, b, h, r, s;
		findArea area = new findArea();
		Scanner get = new Scanner(System.in);

		System.out.print("\nEnter Base & Vertical Height of Triangle: ");
		b = get.nextDouble();
		h = get.nextDouble();
		area.findTriangle(b, h);

		System.out.print("\nEnter Length & Breadth of Rectangle: ");
		l = get.nextDouble();
		b = get.nextDouble();
		area.findRectangle(l, b);

		System.out.print("\nEnter Side of a Square: ");
		s = get.nextDouble();
		area.findSquare(s);

		System.out.print("\nEnter Radius of Circle: ");
		r = get.nextDouble();
		area.findCircle(r);
	}
}	

Output:
Java Program to calculate Area using Abstract Class and Methods

Download Source Code

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: