What is purpose of constructors in Abstract classes?

Abstract class is a class, which cannot be directly instantiated. Abstract class may or may not have abstract methods. A class can be declared abstract, by specifying abstract keyword.

An abstract method is a method, whose declaration is provided in abstract class, and this method’s definition is provided by any of the Derived class.

As known, an abstract class cannot be instantiated, i..e object of an abstract class cannot be created, directly.

In any class, Constructor just initializes data members, and does not create an object.
Similarly Constructor in Abstract class does not create an object, and just initializes data members.

Also, note that
1. Constructor cannot be abstract.
2. super(), this() and this. can be used in abstract classes, as shown in below example.

abstract class Abs1{
	int i,j;
	Abs1(){
		System.out.println("Abs1() Constructor");
	}

	Abs1(int i, int j)
	{
		this();
		this.i = i;
		this.j = j;
		System.out.println("Abs1(int i, int j) Constructor");
	}
}

public class AbstractDemo extends Abs1{

	AbstractDemo(){
		System.out.println("AbstractDemo() Constructor");
	}
	public static void main(String args[])
	{
		AbstractDemo obj = new AbstractDemo();
		System.out.println("in main() method");
	}
}

Output:
Abs1() Constructor
AbstractDemo() Constructor
in main() method

Below is an example in which a derived class from an abstract class, is also abstract

package p1;

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

	static void test()
	{
		System.out.println("test()");
	}

	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();

		A1.test();
	}
}

Below is an example in which an abstract class implements an interface.


interface MyAbc
{
	//constants can be declared in interface
	final int CHECK = 1;

	public void met1();

	public void met2();
}

abstract class X1 implements MyAbc
{

	public void met2(){
		System.out.println("met2() implemented in X1");
	}

	abstract public double myMet();
}

class Y1 extends X1
{
	public void met1()
	{
		System.out.println("met1() implemented in Y1");
	}

	public double myMet()
	{
		System.out.println("myMet() implemented in Y1");

		return 0.0;
	}
}

public class AbstractAndInterface {
	public static void main(String args[])
	{
		Y oy = new Y();

		oy.met1();
		oy.met2();

		System.out.println(MyAbc.CHECK);
	}
}

You may also like to read:
What is purpose of this keyword in Java
What is the purpose of super keyword in java

Leave a Reply