The abstract keyword in Java


A class which contains the abstract keyword in its declaration is known as abstract class. Abstract classes may or may not contain abstract methods, i.e., methods without body. But, if a class has at least one abstract method, then the class must be declared abstract.

If a class is declared abstract, it cannot be instantiated. To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it. If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

Let us see a simple example −

Example

abstract class CricketLeague {
   abstract void CSK();
}
class IPL extends CricketLeague {
   @Override
   void CSK() {
      System.out.println("Team Chennai...");
   }
}
public class Main {
   public static void main(String[] args) {
      IPL i = new IPL();
      i.CSK();
   }
}

Output

Team Chennai...

Let us see another example wherein we are working with abstract methods. Remember, an abstract method contains a method signature, but no method body. Instead of curly braces, an abstract method will have a semi-colon (;) at the end −

Example

abstract class CricketLeague {
   abstract void CSK();
   void KKR(){
      System.out.println("Team Kolkata...");
   }
}
class IPL extends CricketLeague {
   @Override
   void CSK() {
      System.out.println("Team Chennai...");
   }
}
public class Main {
   public static void main(String[] args) {
      IPL i = new IPL();
      i.CSK();
      i.KKR();
   }
}

Output

Team Chennai...
Team Kolkata...

Updated on: 23-Sep-2019

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements