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

    Join Date
    Feb 2012
    Rep Power

    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() ?

    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
    Shanghai, An tSín
    Rep Power
    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
    Rep Power

    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