Friday, 20 December 2013

Unknown

When to use abstract methods in Java?


Why you would want to declare a method as abstract is best illustrated by an example. Take a look at the code below:
/* the Figure class must be declared as abstract 
   because it contains an abstract method  */

public abstract class Figure
{
 /* because this is an abstract method the 
    body will be blank  */
 public abstract float getArea(); 
}

public class Circle extends Figure
{
 private float radius;

 public float getArea()
 {
  return (3.14 * (radius * 2));  
 }
}

public class Rectangle extends Figure
{
 private float length, width;

 public float getArea(Figure other)
 {
  return length * width;
 }
}

In the Figure class above, we have an abstract method called getArea(), and because the Figure class contains an abstract method the entire Figure class itself must be declared abstract. The Figure base class has two classes which derive from it – called Circle and Rectangle. Both the Circle and Rectangle classes provide definitions for the getArea method, as you can see in the code above.

But the real question is why did we declare the getArea method to be abstract in the Figure class? Well, what does the getArea method do? It returns the area of a specific shape. But, because the Figure class isn’t a specific shape (like a Circle or a Rectangle), there’s really no definition we can give the getArea method inside the Figure class. That’s why we declare the method and the Figure class to be abstract. Any classes that derive from the Figure class basically has 2 options: 1. The derived class must provide a definition for the getArea method OR 2. The derived class must be declared abstract itself. 

Unknown

About Blog No Baap -

Since 2016 BlogNoBaap has been bringing you the very best in all types of web resources. Posted daily, and delivered straight to your inbox each morning.

Subscribe to this Blog via Email :