Abstract in Java

Table of Contents

Before going into the concept of Abstract keyword,it is important to the meaning of Data Abstraction or specifically Abstraction

What is Data Abstraction?

It is a mode of representation where only the functionality of it is shown but the details of implementation are kept hidden. It is like a product, which a company produces to be sold, where it only shows the specification of it to the consumers while they don’t show you detailing of the production.

While using Abstract class, you must keep some points handy.

Points to be remembered

  • An abstract class must be declared with an abstract keyword.
  • It can have abstract and non-abstract methods.
  • It cannot be instantiated.
  • It can have final, constructors, and static methods also.

Now look into the following example for understanding of them at once.

abstract class Simple
{
  Simple()//Constructor created
  {
   System.out.println("Hello3");
  }
  abstract void meth();//Abstract method
  static void meth2()//Static method
  {
   System.out.println("Hello2");
  }
  final void meth3()//Final method
  {
   System.out.println("Hello4");
  }
}
class Sample extends Simple
{
  void meth()
  {
   System.out.println("Hello");
  }
  public static void main(String args[])
  {
   Sample obj = new Sample();
   obj.meth();
   Simple.meth2();
   obj.meth3();
  }
}

Hope, each of the points till now has been made cleared with the above example, now just have a look at the following example, the creation of the object is different.

abstract class Simple
{
  abstract void meth();
 }
class Table extends Simple
{
  void meth()
  {
    System.out.println("Table");
  }
}
class Sample
{
  public static void main(String args[])
  {
   Simple obj = new Table();//Creating object is different
   obj.meth();
  }
}

So, what is the meaning of this line or how a programmer will define it?

This single statement actually performs three actions,which are:

  • Declaration
  • Instantiation
  • Initialization

Now, let’s define it…

Simple obj = new Table();

Simple obj is a variable declaration that simply declares to the compiler that the name obj will be used to refer to an object whose type is of Simple. And the new() operator instantiates the Table class, thereby creating a new Table object, and the same Table initializes the object with its default value.

Previous Interface in Java
Next Method Overloading in Java

Leave a Reply