#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    14
    Rep Power
    0

    Abstract Class vs "Indiviudal Class"


    Hi, i'm new in Java, so here is a doubt about an Abstract class.
    For instance, if we had the following Super Abstract Class and two Sub classes, what is the advantage of using the Abstract class ? Why we can't just "eliminate" the super abstract class once the subclasses dont share the same implementation of the method getArea() ?

    Code:
    public abstract class Shape{
    
    public abstract int getArea(int x);
    
    }
    
    public class Square extends Shape{
    
    public Square(){}
    
    public int getArea(int x){ return x*x}
    
    }
    
    public class Circle extends Shape{
    
    public Circle(){}
    
    public int getArea(int x){ return pi*x*x}
    }
  2. #2
  3. kill 9, $$;
    Devshed Supreme Being (6500+ posts)

    Join Date
    Sep 2001
    Location
    Shanghai, An tSín
    Posts
    6,897
    Rep Power
    3886
    You'd generally want to use an abstract class if there is some code that you want the subclasses to inherit.

    In a case like this, where all the methods in your abstract class are themselves abstract, you'd be better to use an interface instead.
  4. #3
  5. --
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Jul 2012
    Posts
    3,920
    Rep Power
    1045
    Hi,

    This isn't a good example, so it's kind of hard to explain the use of abstract classes with this code.

    The point of the Shape class is to specify that all subclasses (i. e. concrete shapes) have a method to calculate the area. However, this isn't a good generalization, because shapes obviously aren't all defined by exactly one parameter. And like ishnid already said, you'd rather use an interface in this case.
    The 6 worst sins of securityHow to (properly) access a MySQL database with PHP

    Why can’t I use certain words like "drop" as part of my Security Question answers?
    There are certain words used by hackers to try to gain access to systems and manipulate data; therefore, the following words are restricted: "select," "delete," "update," "insert," "drop" and "null".

IMN logo majestic logo threadwatch logo seochat tools logo