How and when to use an abstract class

94,844

Solution 1

You'd use an abstract class or interface here in order to make a common base class/interface that provides the void draw() method, e.g.

abstract class Shape() {
  void draw();
}

class Circle extends Shape {
   void draw() { ... }
}

...

Shape s = new Circle();
s.draw();

I'd generally use an interface. However you might use an abstract class if:

  1. You need/want to provide common functionality or class members (e.g. the int i member in your case).
  2. Your abstract methods have anything other than public access (which is the only access type allowed for interfaces), e.g. in my example, void draw() would have package visibility.

Solution 2

An abstract class has an "is-a" type relationship with your subclasses. So for instance, you could have an abstract class Shape which has stuff any shape has (like a draw function), and then a class SquareShape. Every squareshape is a shape, but not all shapes are squareshapes.

In you example you have 2 shape-types, and a class that has 2 instances of these. That is not a relationship you should define with abstract I think.

You might want to do something with your names though, because this is a rather small example, it's hard to see the real implications of the files, and how they should work.

Solution 3

An abstract class is a class, which has at least one method not implemented, or the keyword abstract. For example, an abstract method may look like this:

public abstract String myMethod(String input);

(note that the method ends with a semi-colon).

And a class may look like this:

public abstract class MyClass {

    public abstract String myMethod(String input);

    public String anotherMethod(String input) {
        return intput + " additional text";
    }
}

An abstract class cannot be instantiated. Abstract classes require a subclass to implement the missing behaviour so that it can be instantiated.

The main goal of an abstract class is to provide shared implementation of common behaviour - promoting the reuse of code.

In Java the same effect can be achieve by using a composition of classes instead of inheritance from broadly defined abstract classes. This allows more modular, function specific classes promoting code reuse, that in turn increase maintainability.

My advice would be to use abstract class only when strictly necessary, and in particular avoid using it as a trick bag full of all sorts of functionality.

In Scala one would use traits, which are an elegant way to solve this. It does however, require a lot of attention to get it right through.

Edit: Starting Java 8, default methods in interface are another way to add common behavior.

Solution 4

Common things + Uncommon things = Abstract class

When to use?

An abstract class is best suited for the scenarios where there is a lot of reusable code which you don't want to write again and again + There are few things which are specific to each class.

Example?

Ceremony:

Common things: Sing Anthem, Hoist Flag etc
Specific things: Indian Flag, Indian anthem(For India), China Flag, China anthem(For China) etc.

enter image description here

How to use it?

1) Create an abstract class
2) Put everything in public methods which are common
3) Put everything in abstract methods which are specific to child classes

Where is the sample code?

Base class:

public abstract class BaseCeremony{

    Flag natonalFlag;
    Anthem anthem;

    //**** Common Task ******//
    public void startCeremony(){
        configure();
        hoistFlag();
        singAnthem();
    }

    public void hoistFlag(){
        natonalFlag.hoist();                       
    }

    public void singAnthem(){
        anthem.anthem();                       
    }

    private void configure(){
        natonalFlag = provideFlag();
        anthem = provideAnthem();
    }

    //**** Differs in all part ******//
    public abstract Flag provideFlag();
    public abstract Anthem provideAnthem();

}

In the child class, you just have to provide the implementation of the uncommon part.
ChildClass

public class IndianCeremony extends BaseCeremony{

       public Flag provideFlag(){
            return new IndianFlag();
       }

       public Anthem provideAnthem(){
            return new IndianAnthem();
       }
}

Bonus

  • An abstract class is an incomplete class that is why you can not create its objects.
  • An abstract class should have at least one abstract method to qualify as an abstract class
  • Example of abstract class implementation in Android

Solution 5

sample example for using abstract class in java.

package use_of_abstract;

abstract class Shapes 
{
   int i=1;

   abstract void draw();
   abstract void color(String mycolor);

   //not an abstract method
   void fill()
   {
      System.out.println("Non-Abstract Method -> Fill"); 
   }

   //not an abstract method
   String anotherMethod(String input) 
   {
       return input + " additional text";
   }

}

package use_of_abstract;

public class Shape_One extends Shapes 
{
    int i=1;

    @Override
    void draw() 
    {
        System.out.println("This is Shape One:"+i);
    }

    @Override
    void color(String mycolor) 
    {
        System.out.println("This is Shape One:"+mycolor);

    }

    @Override
    String anotherMethod(String anotherMethod) 
    {
        System.out.println("This is Shape One:"+anotherMethod);
        return anotherMethod;

    }

}

package use_of_abstract;

public class Shape_Two extends Shapes
{
    int i=2;

    @Override
    void draw() 
    {
        System.out.println("This is Shape Two :"+i);
    }

    @Override
    void color(String mycolor) 
    {
        System.out.println("This is Shape Two Color:"+mycolor);
    }

    @Override
    String anotherMethod(String anotherMethod) 
    {
        System.out.println("This is Shape Two:"+anotherMethod);
        return anotherMethod;

    }

}

package use_of_abstract;

import java.awt.Color;

public class Shape_Main 
{

    public static void main(String args[])
    {
        Shape_One s1;
        Shape_Two s2;

        s1=new Shape_One();
        s2= new Shape_Two();

        s1.draw();
        s2.draw();

        s1.fill();
        s2.fill();

        s1.color("Blue");
        s2.color("Green");


        s1.anotherMethod("HELLO..............Its Another Method 1");
        s2.anotherMethod("HELLO..............Its Another Method 2");


    }   
}
Share:
94,844
Admin
Author by

Admin

Updated on July 20, 2021

Comments

  • Admin
    Admin almost 3 years

    This is my test program in Java. I want to know how much abstract class is more important here and why we use abstract class for this.

    Is it a mandatory or is it best method; if so how?

    class Shape1 {
        int i = 1;
        void draw() {
            System.out.println("this is shape:" + i);
        }
    }
    
    class Shape2 {
        int i = 4;
        void draw() {
            System.out.println("this is shape2:" + i);
        }
    }
    
    
    class Shape {
        public static void main(String args[]) {
            Shape1 s1 = new Shape1();
            s1.draw();
    
            Shape2 s2 = new Shape2();
            s2.draw();
        }
    }
    
  • Nanne
    Nanne almost 13 years
    This is not true. an abstact class can have tons of impelementations. It can also have abstract methods that look to the extending class to implement, but it certainly can have implementation. Interfaces don't have implementation, abstract classes can (yes, you can have an abstract class with only abstract methods, but it doesn't have to be that way). You can't have an instance of an abstract class ofcourse.
  • Alex Lockwood
    Alex Lockwood about 11 years
    Abstract classes don't necessarily need to have abstract methods... you could define an abstract class which has all of its methods implemented, for example.