Abstract keyword in Java

  • 10 March 2020
  • ADM

 

Abstract keyword in Java - images/logos/java.jpg

 

Table of content View all

  • abstract
  • assert
  • boolean
  • break
  • byte
  • case
  • catch
  • char
  • class
  • const (not used)
  • continue
  • default
  • do
  • double
  • else
  • enum
  • extends
  • final
  • finally
  • float
  • for
  • goto (not used)
  • if
  • implements
  • import
  • instanceof
  • int
  • interface
  • long
  • native
  • new
  • package
  • private
  • protected
  • public
  • return
  • short
  • static
  • strictfp
  • super
  • switch
  • synchronized
  • this
  • throw
  • throws
  • transient
  • try
  • void
  • volatile
  • while

 

Abstract keyword

The abstract keyword is used in Java for abstraction. The abstraction is the process of selecting data and displaying only the relevant details to the object. If helps to reduce the programing complexity and the efort.

Syntax

public abstract class ADemoClass
{
    //declare other methods and fields
 
    //an abstract method
    abstract void someMethod();
}

Basic rules

  • The abstract keyword can be used only on classes and methods.
  • An abstract class cannot be instantiated.
  • An abstract method doesn't have a body.
  • An abstract method cannot be private.
  • An abstract method cannot be static.
  • An abstract method cannot be synchronized.
  • The abstract keyword cannot be combine with final.
  • If a class extends an abstract class it has to implement all the abstract method.
  • An abstract class can be declared as ineer class.

Example

Will take a simple classic example of animals and the fact that all have at least one think in common: "speak" (make a sound). Then the extention to every species will have the details of how to "speak".

public abstract class Animal 
{    
    public abstract void speak();
}

The implementation of Dog class.

public class Dog extends Animal 
{
    @Override
    public void speak() 
    {
        System.out.println("Dog says Woof Woof");
    }
}

The implementation of Cat class.

public class Cat extends Animal 
{
    @Override
    public void speak() 
    {
        System.out.println("Cat says Meow Meow");
    }
}

The implementation of Cow class.

public class Cow extends Animal 
{
    @Override
    public void speak() 
    {
        System.out.println("Cow says Moo moo");
    }
}

Usage

public class Main 
{
    public static void main(String[] args) 
    {
    	System.out.println("Java abstraction example");
    	System.out.println("");
        Animal animal1 = new Dog();
        animal1.speak();
 
        Animal animal2 = new Cat();
        animal2.speak();

        Animal animal3 = new Cow();
        animal3.speak();		
    }
}

Output

As you can see each instance will output differently based on each implementation.

Java abstraction example

Dog says Woof Woof
Cat says Meow Meow
Cow says Moo moo

 

References