-4

As we all know that we cant instantiate an abstract class. But look into this code:

abstract class Bike  
{  
    int limit=30;  
    Bike()
    {
        System.out.println("constructor is invoked");
    } 

    void getDetails()
    {
        System.out.println("it has two wheels");
    }  
    abstract void run();  
}  

class Honda extends Bike{  
    void run()
    {
        System.out.println("running safely..");
    }  

    public static void main(String args[])
    {  
        Bike obj = new Honda();  
        obj.run();  
        obj.getDetails();  
        System.out.println(obj.limit);  
    }  
} 

Here we are creating object of Honda class by using reference of Superclass(Abstract class). Again we know that when ever subclass object is created 1st the super class constructer is called. Now the super class constructor is called then we know that first object is created in memory then constructed in called. Then why here object is not created.

Soumya
  • 233
  • 2
  • 9
  • 1
    Provide an error message you are getting. – MrTux Aug 21 '14 at 20:36
  • 1
    in compiler's view, it doesn't care if a abstract class can be instantiate or not. but, as language designers or users, people never want uncompleted object to be instantiated. – Jason Hu Aug 21 '14 at 20:36
  • constructor is invoked running safely.. it has two wheels 30 – Soumya Aug 21 '14 at 20:42

3 Answers3

2

You can create instances of an abstract class, but only through instantiating a subclass. For example, you cannot create the abstract Bike class by saying:

Bike b = new Bike(); //error

Because there is no executable code for the run() method.

b.run(); // uh oh.

However, since all non-abstract subclasses must implement the method, we know that b.run() will be safe, because b must be a non-abstract subclass of Bike.

clcto
  • 9,530
  • 20
  • 42
1

I'm not really sure if I understood what you mean, but here it is: The abstract class only serves as a model for concrete classes, that's why it can't be instantiated. The object created is of Honda type that extends the abstract class Bike.

0

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.

Would recommend some reading:

Abstract Classes

How can abstract classes have references but not objects?

Cheers !!

Community
  • 1
  • 1
Sachin Thapa
  • 3,559
  • 4
  • 24
  • 42