Abstract class in Java

  • If you want to define an abstraction with some common functionality, then use abstract class.
  • A class which is declared using abstract keyword is called abstract class.
  • You can define constructors in an abstract class.
  • You can create reference variables of an abstract class, but you cannot instantiate it.
  • It is not necessary for an abstract class to have abstract methods. In other words, an abstract class may or may not have any abstract methods.
  • If a class has one or more abstract methods then that class must be declared an abstract class and the derived class must implement all the abstract methods. If a derived class does not implement any one of the abstract methods then that derived class need to be marked an abstract class.
  • You can declare instance and static variables in an abstract class. Also, an abstract class can have instance and static methods.
  • An abstract class can extend any other class and implement other interfaces.
  • You cannot define an abstract class as a final class, doing so will give compile time error.

Abstract Method in Java

A method that has no body is known as an abstract method.

Syntax-

access-modifier abstract return-type methodName(parameters);

Example-

public abstract void eat();

Examples of Abstract class

abstract class Shape
{
	public abstract int area(int r);
	public void display()
	{
		System.out.println("I am a shape")
	}
}
class Square
{
	public void perimeter(int s)
	{
		System.out.println("Perimeter of square = " +4*s);
	}
	public static void main(String args[])
	{
		Square s = new Square();
		s.perimeter(2);
	}
}

Output

compile time error.

The above code will give compile time error as the derived class Square has not implemented abstract method area() of Shape class.

abstract class Animal
{
	String name;
	public Animal(String name)
	{
		this.name = name;
	}
	public abstract void sound();
}
class Dog extends Animal
{
	public Dog(String name)
	{
		super(name);
	}
	public void sound()
	{
		System.out.println("Bark");
	}
	public static void main(String args[])
	{
		Animal a = new Dog("German Shepherd");
		System.out.println("Name = "+a.name);
		a.sound();
	}
}

Output

Name = German Shepherd
Bark

As you can see we can call abstrac class constructor using super() keyword.