purpose of abstract keyword

abstract keyword in Java, can be used for a method and class as well.

Why a method need to be declared abstract?
Generally methods which cannot have implementation in Base classes are declared abstract, so that these abstract methods can further be implemented by Base classes. Declaring a method as abstract, specify that current class does not provide any definition and it is up to derived classes to provide method body for abstract methods.

Why a class need to be declared abstract?
class is declared abstract in following cases.

  1. A class having an abstract method need to be declared abstract.
  2. If a derived class does not implement all abstract methods of base class, then the derived class need to be declared abstract.
  3. Also, a class implementing an interface need to be declared abstract, if the class does not implement any of the interface methods.

abstract classes cannot be instantiated.

Below is simple example of abstract class and abstract method

abstract class A11{
	public void met1(){
		System.out.println("met1() in A1");
	}

	//derived class of A11 need to define met2() method
	abstract public void met2();

	abstract public void met3();
}

class B11 extends A11{
	public void met2()
	{
		System.out.println("met2() in B1");
	}

	public void met3()
	{
		System.out.println("met3() in B1");
	}
}

public class SimpleAbstract {

	public static void main(String[] args) {
		//A11 ghj = new A11(); //abstract classes cannot be instantiated
		B11 obj = new B11();

		obj.met1();
		obj.met2();
		obj.met3();
	}

}


Another example of abstract:

abstract class A1{
	public void met1(){
		System.out.println("met1() in A1");
	}

	abstract public void met2();

	abstract public void met3();
}


//class B1 need to be declared abstract as it does not implement met3() of A1 class
abstract class B1 extends A1{
	public void met2()
	{
		System.out.println("met2() in B1");
	}
}

class C1 extends B1{
	public void met3()
	{
		System.out.println("met3() in C1");
	}
}
public class AbstractDemo {

	public static void main(String[] args) {
		C1 obj = new C1();

		obj.met1();
		obj.met2();
		obj.met3();
	}

}


abstract key word with interfaces(coming soon…)

2 thoughts on “purpose of abstract keyword”

Leave a Reply