View Full Version : Java
kishorekumar
Nov 12, 2006, 11:09 PM
We can not instantiate an abstract class. But we can write a constructor in abstract class. If we are not able to create an object, then how and why is it possible to create a constructor in an abstract class?
LTheobald
Nov 13, 2006, 06:18 AM
The definition of an abstract class is that it needs to have one or more abstract methods. It can also have a number of non abstract methods - hence why you can have a constructor. For example, the below is valid:
public abstract class QuickTest {
public QuickTest() {
// Constructor
}
// Abstract method
public abstract void sayGoodBye();
// Non-abstract method
public void sayHello() {
System.out.println("Hello World");
}
}
kishorekumar
Nov 13, 2006, 06:28 AM
We can not instantiate an abstract class. But we can write a constructor in abstract class. If we are not able to create an object, then how and why is it possible to create a constructor in an abstract class?
Thanks LTheobald for the reply...
Yes. What u said is true. We can write. But I wonder what's the use of constructor. Now I've found that answer. We may be using private instance variables. So to initialize them we have to use constructor. An object is not created by the constructor. It's the new which creates. After creating object it executes constructor to initialize the variables.
chowdari
May 26, 2007, 02:41 AM
We can not instantiate an abstract class. But we can write a constructor in abstract class. If we are not able to create an object, then how and why is it possible to create a constructor in an abstract class?
Every class is responsible to initialize its instance variables.If subclass calls its abstract super class then it is the constructor that ini... the instance variables.
Suddashil
Sep 24, 2007, 01:35 AM
Abstract class is a class which can not be initialized but inheritated. Inheritance means properties of super class object is inheritated by sub class. So, object of abstract class is created for it's sub class only while inheritance mechanism takes place. So constructor is needed.