Use of constructor in abstract class?


  1. public abstract class TestEngine  
  2. {  
  3.    private String engineId;  
  4.    private String engineName;  
  5.    
  6.    public TestEngine(String engineId , String engineName)  
  7.    {  
  8.      this.engineId = engineId;  
  9.      this.engineName = engineName;  
  10.    }  
  11.    //public gettors and settors  
  12.    public abstract void scheduleTest();  
  13. }  
  14.    
  15.    
  16. public class JavaTestEngine extends TestEngine  
  17. {  
  18.    
  19.    private String typeName;  
  20.    
  21.    public JavaTestEngine(String engineId , String engineName , String typeName)  
  22.    {  
  23.       super(engineId , engineName);  
  24.       this.typeName = typeName;  
  25.    }  
  26.    
  27.    public void scheduleTest()  
  28.    {  
  29.      //do Stuff  
  30.    }  
  31. }

So in my code TestEngine is an abstract having a constructor to initiate its two members

and the JavaTestEngine is a sub class of my abstract TestEngine which inheriting the two variables of the parent class

hope u Got why we need a constructor for the abstract class.
Note

All abstract class are not pure abstract, partially they are . So if u need a pure abstract class Go for an Interface.

In java all classes having a constructor (default)

U can call the Test Engine like ....

 
TestEngine engine = new JavaTestEngine("E001""JAVA TEST ENGINE" , "JAVA"); 

 1. What is the use of having constructor in abstract class? Any how we cant create instance on abstract class. so whats the use of constructor?"

The purpose of abstract class is to provide common information for the subclasses.The abstract classes cannot be instantiated.You will get a compile error.


"2. When we are not able to create instance of abstract class, whats the use of having concrete methods(fully coded) in abstarct class? How can we call them without an instance? "


An abstract class can have methods with full body apart and abstract method.
This is especially usefull when extending classes.Say,you have an super class Animal and sub-classes Dog,Cat,Cow etc.All the different type of animals have one thing comon.ie,sound.So the Animal class has methods to define these sub-classes and also a method called sound().Though this method does nothing.It is only used in subclasses and implemented.It is just declared in Animal class but not defined.

See the code below:

public abstract class Animal{
public abstract void sound();

private String type;

public Animal(String atype){
type=new String(atype);
}
public String toString(){
return "This is a "+ type;
}
}

public class Dog extends Animal{
public Dog(String aname){
super("Dog");
this.aname=aname;
}
public void sound(){
System.out.println("woof woof");
}
}

similarly you can do for cat,cow etc.

This is known as polymorphisim.The advantage is that the single method can behave differently,depending on the type of object it is called.