0

Possible Duplicate:
What is the use of creating a constructor for an abstract class in Java?

Example:

abstract public class AbstractDemo 
{
    private int ab;
    public AbstractDemo() 
    {
        ab=10;
    }

    public int getAb()
    {
        return ab;
    }

    public void abstractMethod()
    {
        //On the line below it gives error.
        AbstractDemo demo=new AbstractDemo();
    }

}

Edited to format code

Community
  • 1
  • 1
DMS
  • 808
  • 2
  • 20
  • 34
  • hope it is duplicate question, i asked this already [link] http://stackoverflow.com/questions/5404168/constructors-in-abstract-classes – developer Mar 30 '11 at 06:18
  • http://stackoverflow.com/questions/504977/why-cant-i-create-an-abstract-constructor-on-an-abstract-c-class – Mitch Wheat Mar 30 '11 at 06:19
  • how is this an exact duplicate? the problem is his instantiate of Abstract base classes directly. In fact, its not even the same language as the questions referenced!!! – J T Mar 30 '11 at 06:27

4 Answers4

2

You can't make an instance of an abstract class. The constructor is there for when you have a class that implements it, you can call it (implicitly, or using super.), and you can put code in there that should be executed when an instance is made.

Nanne
  • 64,065
  • 16
  • 119
  • 163
2

In my opinion, the constructor in abstract class can do some init work which all the subclass do not need to repeat in its own construtor.

James.Xu
  • 8,249
  • 5
  • 25
  • 36
  • +1. We only need constructor in abstract class for doing general operations. @Dinesh: we can not use `new` for abstract class and that's why you are having error. – Harry Joy Mar 30 '11 at 06:23
1

Criticism of code:

Abstract base classes (ABC) can't be instantiated directly - hence the term Abstract. The following is therefore syntactically incorrect in Java:

AbstractDemo demo=new AbstractDemo();

You need to replace this with something else, or delete the method entirely.

Use of constructors:

When you instantiate a class that inherits from this abstract base class, you can call the constructor of the abstract base class to assign any properties private the ABC.

Such as:

public class DerivedDemo extends AbstractDemo {

    public DerivedDemo (int a, int b) {

        super(); //calls constructor
    }
}
J T
  • 4,946
  • 5
  • 28
  • 38
0

A constructor is for initializing the fields of the object when you create an instance of that class. This is no different for an abstract class. While you can't directly create an instance of an Abstract class, you can create an instance of a concrete class that derives from an abstract class.

MeBigFatGuy
  • 28,272
  • 7
  • 61
  • 66