tags:

views:

89

answers:

5

Possible Duplicates:
Why do abstract classes in Java have constructors?
abstract class constructors?

We know abstract class can't be instantiated but on the other hand it can have constructor. Please explain why abstract class can have a constructor ? How compiler handles this situation?

A: 

Abstract class can have constructor that can be called in derived classes. So usually constructor is marked as protected in abstract class.

DixonD
constructors are not inherited
Georgy Bolyuba
A: 

Duplicate:

volothamp
@volothamp you have enough points to vote to close the question as a duplicate
Mark
The FAQ says: "3000 Vote to close, reopen, or migrate any questions". He only has 1000, am I missing something?
Andrei Fierbinteanu
A: 

This is probably not the best explanation but here it goes. Abstract classes enforce a contract much like an interface but can also provide implementation. Classes that inherit from the abstract class also inherit the implemented functions and depending on the language you can override the default implementation as needed.

antonlavey
A: 

Say you have abstract class A:

abstract class A {
  private int x;

  public A(int x) {
    this.x = x;
  }

  public int getX() {
    return x;
  }
}

Notice, that the only way to set x is through the constructor, and then it becomes immutable

Now I have class B that extends A:

class B extends A {
  private int y;

  public B(int x, int y) {
    super(x);
    this.y = y;
  }

  public int getY() {
    return y;
  }
}

Now B can also set x by using super(x) but it has on top of that an immutable property y.

But you can't call new A(5) since the class is abstract you need to use B or any other child class.

Andrei Fierbinteanu
A: 

The constructor of an abstract class is used for initializing the abstract class' data members. It is never invoked directly, and the compiler won't allow it. It is always invoked as a part of an instantiation of a concrete subclass.

For example, consider an Animal abstract class:

class Animal {
    private int lifeExpectency;
    private String name;
    private boolean domestic;

    public Animal(String name, int lifeExpectancy, boolean domestic) {
        this.lifeExpectency = lifeExpectancy;
        this.name = name;
        this.domestic = domestic;
    }

    public int getLifeExpectency() {
        return lifeExpectency;
    }

    public String getName() {
        return name;
    }

    public boolean isDomestic() {
        return domestic;
    }
}

This class takes care of handling all basic animal properties. It's constructor will be used by subclasses, e.g. :

class Cat extends Animal {

    public Cat(String name) {
        super(name, 13, true);
    }

    public void groom() {

    }
}
Eyal Schneider