Ask Me Help Desk

Ask Me Help Desk (https://www.askmehelpdesk.com/forum.php)
-   Java (https://www.askmehelpdesk.com/forumdisplay.php?f=440)
-   -   Java (https://www.askmehelpdesk.com/showthread.php?t=42476)

  • Nov 12, 2006, 11:09 PM
    kishorekumar
    Java
    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?
  • Nov 13, 2006, 06:18 AM
    LTheobald
    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");
      }
    }

  • Nov 13, 2006, 06:28 AM
    kishorekumar
    Quote:

    Originally Posted by kishorekumar
    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.
  • May 26, 2007, 02:41 AM
    chowdari
    Quote:

    Originally Posted by kishorekumar
    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.
  • Sep 24, 2007, 01:35 AM
    Suddashil
    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.