DEV Community

Shweta Kadam
Shweta Kadam

Posted on

Abstract Keyword in Java

Today revising the abstract keyword. Interface uses abstract keyword implicitly. Let's see in detail about the abstract keyword in every scenario.
1.Variable
2.Class
3.Method

1.Variable

A variable cannot be marked as abstract.

2.Class

I) If a class is marked as abstract ,it cannot be instantiated i.e you cannot create an object of that class.
II)If another class extends an abstract class it has to compulsorily override all the methods in that class.

abstract class A{
abstract public void m1();
}
//SOLUTION 1:class B has to override all the methods of class A 
class B extends A{

}
//SOLUTION 2:class B can mark itself as abstract as shown below

class B extends A{

}

Enter fullscreen mode Exit fullscreen mode

3.Method

I)If a programmer does not know the implementation of a method it can mark itself as abstract.
II)An abstract method should be an abstract class
NOTE:
AN abstract method should not have a body.

abstract public void display();
Enter fullscreen mode Exit fullscreen mode

Below is just a small program to demonstrate the use of abstract

abstract class A{
abstract void m1();        //m1() is abstract so class A shd be abstract
}

abstract class B extends A{
 void m1(){
   System.out.println("A");    //B overrides m1()
}

abstract void m2();
}

abstract C extends B{
//class C doesn't know the implementation of m2 and hence it marks itself as abstract.

void m3(){
  System.out.println("C"); 
}}

class D extends C{
} //This alone will give COMPILE ERROR BECOZ D MUST OVERRIDE m2()

Enter fullscreen mode Exit fullscreen mode

That's all for abstract keyword.If any mistake or any info which I missed,please feel free to correct me in the comments.

Happy Learning :)

Top comments (0)