Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » FundamentalRSS Feeds

Abstract method

Posted By: Frazer Jones     Category: Java     Views: 24014

This article explains about an abstract method in java with examples.

Abstract methods are those which need to be implemented in subclass / child class. Abstract methods are only defined in  superclass / parent class but with no body.

Syntax of Abstract Method

abstract class clsName
{
     // Variable declaration
 
     // Constructor

     // Method
     abstract rtype mthName(params);
}

clsName is a valid identifier in java. It is a class name.
abstract is a keyword to define that method an abstract method.
rtype is return type of a method.
mthName is a method name and valid java identifier.

Example of an Abstract Method

Example 1 : Program that illustrates the use of an abstract method

abstract class Shape
{
      public static float pi = 3.142; 
      protected float height;
      protected float width;

      abstract float area();
}  

class Square extends Shape
{
      Square(float h, float w)
      {
             height = h;
             width = w;
      }

      float area()
      {
            return height * width;
       }
}

class Rectangle extends Shape
{
      Rectangle(float h, float w)
      {
             height = h;
             width = w;
      }

      float area()
      {
             return height * width;
      }
}

class Circle extends Shape
{
      float radius;

      Circle(float r)
      {
             radius = r;
      }

      float area()
      {
            return Shape.pi * radius *radius;
      }
}

class AbstractMethodDemo
{
        public static void main(String args[])
        {
                 Square sObj = new Square(5,5);
                 Rectangle rObj = new Rectangle(5,7);
                 Circle cObj = new Circle(2);

                 System.out.println("Area of square : " + sObj.area());
                 System.out.println("Area of rectangle : " + rObj.area());
                 System.out.println("Area of circle : " + cObj.area());
        }
}

Output
Area of square : 25
Area of rectangle : 35
Area of circle : 12.57
  
Share: 

 
 
 

Didn't find what you were looking for? Find more on Abstract method Or get search suggestion and latest updates.

Frazer Jones
Frazer Jones author of Abstract method is from Melbourne, Australia.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!