Abstract Class in Java

Advertisements

Java Abstract Class

Abstract class is used in situation, when we have partial set of implementation of methods in a class. For example, consider a class have four methods. Out of four methods, we have an implementation of two methods and we need derived class to implement other two methods. In these kind of situations, we should use abstract class.

  • Abstract class is used in situation where we hava partial information.
  • We can't create an object of abstract class.
  • Abstract Class may have abstract methods.
  • Abstract methods must be public.
  • Abstract methods doesnt have body.
  • We must implements all abstract method in derived class.

Example of java abstract class


//AbstractDemo.java

abstract class AbstractClass
{
    public void Display1()
    {
        System.out.print("\n\tThis is Display1() method of Abstract class.");
    }

    public void Display2()
    {
        System.out.print("\n\tThis is Display2() method of Abstract class.");
    }

    public abstract void Display3();
    public abstract void Display4();

}

class DerivedClass extends AbstractClass
{
    public void Display3()
    {
        System.out.print("\n\tThis is Display3() method of Derived class.");
    }

    public void Display4()
    {
        System.out.print("\n\tThis is Display4() method of Derived class.");
    }

}

class AbstractDemo
{
    public static void main(String[] args)
    {
        DerivedClass D = new DerivedClass();

        D.Display1();
        D.Display2();
        D.Display3();
        D.Display4();
    }
}

Advertisement