Abstract class can't be instantiated but can have constructor - little confusing, please explain [duplicate]
Possible Duplicates:
Why do abstract classes in Java h开发者_JAVA技巧ave 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?
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() {
}
}
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.
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.
Abstract class can have constructor that can be called in derived classes. So usually constructor is marked as protected in abstract class.
精彩评论