- public abstract class TestEngine
- {
- private String engineId;
- private String engineName;
- public TestEngine(String engineId , String engineName)
- {
- this.engineId = engineId;
- this.engineName = engineName;
- }
- //public gettors and settors
- public abstract void scheduleTest();
- }
- public class JavaTestEngine extends TestEngine
- {
- private String typeName;
- public JavaTestEngine(String engineId , String engineName , String typeName)
- {
- super(engineId , engineName);
- this.typeName = typeName;
- }
- public void scheduleTest()
- {
- //do Stuff
- }
- }
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.