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?
![]() |
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?
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:
Code:public abstract class QuickTest {
public QuickTest() {
// Constructor
}
// Abstract method
public abstract void sayGoodBye();
// Non-abstract method
public void sayHello() {
System.out.println("Hello World");
}
}
Thanks LTheobald for the reply...Quote:
Originally Posted by kishorekumar
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.
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.Quote:
Originally Posted by kishorekumar
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.
| All times are GMT -7. The time now is 11:05 PM. |