Constructor in Absract Class

This may sound odd, but an abstract class may have constructors, but they cannot be used to instantiate the abstract class. If we write statements to call the constructor the compiler will fail and report the class is "abstract; cannot be instantiated".

we would define a constructor in an abstract class if we are in one of these situations:

  1. Want to perform some initialization (to fields of the abstract class) before the instantiation of a subclass actually takes place
  2.  Defined final fields in the abstract class but we did not initialize them in the declaration itself; in this case, we MUST have a constructor to initialize these fields;


 Note that:

  •  we may define more than one constructor (with different arguments)
  •  we should define all constructors protected (making them public is pointless anyway)
  •  subclass constructor(s) can call one constructor of the abstract class; it may even have to call it (if there is no no-arg constructor in the abstract class)
  •  In any case, don't forget that if we don't define a constructor, then the compiler will automatically generate one for us (this one is public, has no argument, and does nothing).

 Example :
public abstract class AbstractClass{
 String initialValue;   // not initailize the value
 protected AbstractClass(String initialValue) {
  this.initialValue=initialValue;
 }
}
public class DemoAbstractClassConstructor extends AbstractClass{
 public DemoAbstractClassConstructor(String Value) {
  super(Value); // initializing the abstract class filed value through the constructor
 }
 public static void main(String[] args) {
  DemoAbstractClassConstructor obj = new DemoAbstractClassConstructor("2");
  System.out.println("initial value in Abstract Class "+obj.getInitialValue());
 }
 String getInitialValue(){
  return initialValue;
 }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...