22

Here is a scenario in my mind and I have googled, Binged it a lot but got the answer like

"Abstract class has not implemented method so, we cant create the object" "The word 'Abstract' instruct the compiler to not create an object of the class"

But in a simple class where we have all virtual method, able to create an object???

Also, we can define different access modified to Abstract class constructor like private, protected or public.

My search terminated to this question:

Why we can't create object of an Abstract class?

Gaurav Arora
  • 2,243
  • 6
  • 40
  • 57

16 Answers16

68

An abstract type is defined largely as one that can't be created. You can create subtypes of it, but not of that type itself. The CLI will not let you do this.

An abstract class has a protected constructor (by default) allowing derived types to initialize it.

For example, the base-type Stream is abstract. Without a derived type where would the data go? What would happen when you call an abstract method? There would be no actual implementation of the method to invoke.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 2
    that is the real deal, the abstract methods :D – vtortola Apr 23 '10 at 16:35
  • 2
    @Mac Thanks for explaining the words But still the question stand alone : why we cant create an object of the class? Also the default modifier for constructor of Abstract class is Protected but we can define a public constructor then whats the use of public constructor. – Gaurav Arora Apr 23 '10 at 16:37
  • 5
    @Gaurav - in short, because *that is how it is defined*. In the case of `abstract` methods this is to provide sanity, but even without it makes no sense. If you want to be able to create instances - **don't mark it `abstract` ** – Marc Gravell Apr 23 '10 at 16:42
  • @Mac Thanks again for a great reply. Actually I will use a simple class in that case. But still I want to know, if Microsoft allows us to create a public constructor for Abstract classes then I think there is some reason behind this. Else why we can declare public constructor for Abstract classes as there is already protected constructor for Abstract class. I am bit confused here, if we can create private, protected or public constructors for Abstract classes then why we can't create the object? – Gaurav Arora Apr 23 '10 at 16:47
  • The derived class can call the base constructor. Basically, with an "abstract" class you are telling the compiler "This is a concept, not a concrete object." Think "vehicle" vs. "Blue 2006 BMW 325i, serial number xxx". – GalacticCowboy Apr 23 '10 at 17:05
  • Also, you can still declare a variable of the abstract type, but it must be instantiate with one of its concrete descendants. **vehicle myCar = new BMW325i();** – GalacticCowboy Apr 23 '10 at 17:08
  • 1
    Abstract classes are definitions of the protected and/or public methods that child classes must implement. It is a fundamental aspect of OOP. You can't create an instance of a class that has abstract methods in C# because there is no definition for what the abstract method should do. Some other languages, like Delphi 7, will allow instances of abstract classes to be created with predictable results when the instance tries to call an abstract method. – Mike Chess Apr 23 '10 at 17:34
  • @Marc Gravell Why compiler is not blocking when we make constructor as public for abstract class? – VINOTH ENERGETIC Apr 07 '17 at 03:24
  • @Vinoth it is a fair question - ultimately `protected` would have served just fine. Maybe it just wasn't worth the hassle of enforcing it? – Marc Gravell Apr 07 '17 at 07:01
  • @MarcGravell okay. Just to inform you that I checked by keeping constructor as public for abstract class. Compiler is throwing error when we attempt to create object for class. – VINOTH ENERGETIC Apr 07 '17 at 08:35
  • @VINOTHENERGETIC well, yes, of course it would - it is *abstract* - it can't be created; that doesn't change anything I said... – Marc Gravell Apr 07 '17 at 08:35
25

Because it's abstract and an object is concrete. An abstract class is sort of like a template, or an empty/partially empty structure, you have to extend it and build on it before you can use it.

Take for example an "Animal" abstract class. There's no such thing as a "pure" animal - there are specific types of animals. So you can instantiate Dog and Cat and Turtle, but you shouldn't be able to instantiate plain Animal - that's just a basic template. And there's certain functionality that all animals share, such as "makeSound()", but that can't be defined on the base Animal level. So if you could create an Animal object and you would call makeSound(), how would the object know which sound to make?

froadie
  • 79,995
  • 75
  • 166
  • 235
4

It's intended to be used as a base class.

http://msdn.microsoft.com/en-us/library/sf985hc5(VS.71).aspx

The abstract modifier can be used with classes, methods, properties, indexers, and events.

Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes.

Abstract classes have the following features:

  • An abstract class cannot be instantiated.
  • An abstract class may contain abstract methods and accessors.
  • It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
  • A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
hunter
  • 62,308
  • 19
  • 113
  • 113
  • @Hunter Thanks, its right 'An abstract class cannot be instantiated.' But, why we can't create its object although it may contain public or protected constructors. Is there any logic or Framework restriction for the same? – Gaurav Arora Apr 23 '10 at 16:35
  • The framework has been defined such that when we use keyword "Abstract" with a class it cannot be instantiated but can only be inherited. – Ravi Vanapalli Sep 20 '12 at 14:16
3

Abstract classes should have at least one virtual method or property that has no implementation. This is marked with the abstract keyword. Inheriting classes must provide an implementation if they are not abstract themselves. You cannot create an instance of an abstract class because it does not have a complete implementation. If it does, it should not be marked abstract in the first place.

Tom Cabanski
  • 7,828
  • 2
  • 22
  • 25
  • 3
    Wrong. There is nothing wrong with an abstract class w/o abstract members. – H H Apr 23 '10 at 17:03
  • Interesting. Perhaps you can supply a reasonable example of where it makes sense to have an abstract class with no abstract methods or properties. – Tom Cabanski Apr 23 '10 at 17:28
  • Tom, Ok: `class Car: Vehicle {}`. Can you come up with a good case for having an _instance_ of Vehicle? – H H Apr 23 '10 at 17:44
  • @HenkHolterman: Vehicle isn't a great example, since it should almost certainly have some abstract members like `Make` and `Model`. On the other hand, one could have a class with two members which are each defined in terms of the other; some derived classes might override the first, others the second, and some both. For example, a type encapsulating a sequence might include `ToArray` and `ToList` methods, the first of which calls `ToList().ToArray()` and the second of which calls `new List(ToArray())`. Each would make sense as a default behavior if and only if the other is overridden. – supercat Nov 12 '13 at 19:36
3

As an addition to the other answers, you may not be able to create an instance of the abstract class, but you can certainly refer to instances of derived types through the abstract type and use methods or properties that are defined within the abstract base.

abstract class A
{
    public abstract void D();
    public void E() { }
}

class B : A
{
    public override void D() { }
}

class C : A
{
    public override void D() { }
}

...

A a = new B();
a.D();
a.E();

List<A> list = new List<A>() { new B(), new C() };
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
  • And this is what distinguishes extending abstract classes and inheritance: Objects of a subclass using the abstract class type can access methods introduced in the subclass, ie, methods that are not declared in the abstract class. Objects of a subclass using the superclass type (inheritance) cannot access methods introduced in the subclass. – raul Apr 21 '15 at 17:39
2

Simply speaking, an abstract class is like a shell of a class. Not all the methods have implementations, something like a circuit with some wire segments missing. While the majority of it may be constructed, it is up to the users to stick in the wires and resistors in those segments as they see fit.

As to why Java won't let you create it, part of it is just a failsafe (many abstract classes will function just fine without any additions as long as you don't call unimplemented methods).

Ritwik Bose
  • 5,889
  • 8
  • 32
  • 43
1

If we have a class containing pure virtual function then the class is abstract. If we will create an object of the abstract class and calls the method having no body(as the method is pure virtual) it will give an error. That is why we cant create object of abstract class.

Perception
  • 79,279
  • 19
  • 185
  • 195
  • if default constructor of abstract class would be public then it will allow to create an object anywhere then its the part of implemetation if we will get an error at that time So, I don't think this is the robust reason you explain. Sorry to make my hands dirty here :( – Gaurav Arora May 21 '12 at 11:57
  • An abstract class has a protected constructor (by default) allowing derived types to initialize it. – Gaurav Arora May 21 '12 at 11:59
1

We cannot create object for abstract class bcoz ,mostly abstract class contain "abstract methods" ,so abstract methods are incomplete methods.so we cannot estimate the memory of those methods how much they are going to occupy .This is one of the reason why we cannot create object for abstract class.

Alok
  • 2,629
  • 4
  • 28
  • 40
praneeth
  • 11
  • 4
0

Actually when we create an object of a normal class we use Constructor to allocate the memory for that object like

myclass obj=new myclass();

Here using constructorr clr identifies how much memory the object needed depending upon the instance variabless and methods. But in case of abstract classes we cant predict the amount of memory required as we dont implement the abstract methods so its not possible to create object.

robertoia
  • 2,301
  • 23
  • 29
  • The memory used by an instance of a class is not related to the implementation of the methods. The methods' code takes up the space related to the Class itself, not the objects of that class. What point would there be in storing the code of the methods in every object? – Joffrey Jun 23 '15 at 11:59
0

Here is a similar StackOverflow question. In short, it is legal to have a public constructor on an abstract class. Some tools will warn you that this makes no sense.

Whats the utility of public constructors in abstract classes in C#?

Community
  • 1
  • 1
Paul Williams
  • 16,585
  • 5
  • 47
  • 82
0

When we create a pure virtual function in Abstract class, we reserve a slot for a function in the VTABLE(studied in last topic), but doesn't put any address in that slot. Hence the VTABLE will be incomplete.

As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an errror message whenever you try to do so.

Source : Study Tonight

Dharani Dharan
  • 624
  • 1
  • 7
  • 18
0

The reference studytonight :

When we create a pure virtual function in Abstract class, we reserve a slot for a function in the VTABLE(studied in last topic), but doesn't put any address in that slot. Hence the VTABLE will be incomplete.

As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an errror message whenever you try to do so.

msc
  • 33,420
  • 29
  • 119
  • 214
-2

I don't agree with the accepted answer. The reason is that we can have body for pure virtual function.

The answer is that :

When we create a pure virtual function in the class, we reserve a slot for a function in the VTABLE, but doesn't put any address in that slot. Hence the VTABLE will be incomplete. As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an error message whenever you try to do so.

Krishna Oza
  • 1,390
  • 2
  • 25
  • 50
Devesh Agrawal
  • 8,982
  • 16
  • 82
  • 131
  • @Davesh - Acceptance of answer is within the limit of asked question. Your answer is surrounding to the accepted answer. This is by design and you are routing something to Virtual functions. Pure virtual functions are not within the limits of Abstract classes. I can't accept your answer, unless other Techies upgrade your answer. – Gaurav Arora Nov 26 '13 at 21:41
  • @Devesh: This isn't very language-agnostic. Many languages also allow for abstract classes with no abstract methods and an implementation detail such as a vtable has nothing to do with that. – Matti Virkkunen Sep 24 '14 at 06:42
-2

Sorry guys...

You can Create object for an abstract class, if and only if that abstract class does not contains any abstract method.

Here is my Example. Copy it and compile and run.

abstract class Example {
  void display(){
    System.out.println("Hi I am Abstract Class.");
  }
}

class ExampleDemo {
    public static void main(String[] args) {
        Example ob = new Example(){};
        ob.display();
   }
}

So your answer is yes, we can create object for abstract class if it's no Abstract Method. Check my program.

Gagravarr
  • 47,320
  • 10
  • 111
  • 156
lal
  • 5
  • 1
  • 2
    this way you are not exactly creating an object of class Example, but you are creating an object of anonymous class – Kelu Thatsall Dec 16 '14 at 12:06
  • 1
    Sorry but no. You're creating an instance of an anonymous inner class created on-the-fly. Try to use `getClass()` on your `ob` object, you'll see. – Joffrey Jun 23 '15 at 12:02
-3

we can create object for abstract class like this also...

public class HelloWorld
{
    public static void main(String args[])
    {
        Person p = new Person()
        { 
            void eat()
            {
                console.writeline("sooper..");
            } 
        }; 
        p.eat();
    }
}
abstract class Person
{ 
    abstract void eat(); 
} 
Kaspars Ozols
  • 6,967
  • 1
  • 20
  • 33
rk rk
  • 314
  • 1
  • 8
  • This is actually an object of an anonymous class, not of the abstract one – user1781290 Jan 30 '14 at 08:08
  • anonymous class means there should not be any name to the class.But here we have abstract class named person,how can this could be an anonymous class. – rk rk Jan 31 '14 at 11:50
  • It is difficult to explain that in a comment. But there is a similar question here: http://stackoverflow.com/questions/5154533/abstract-class-and-anonymous-class – user1781290 Jan 31 '14 at 12:30
  • I agree this is difficult to explain in comments, this is not a best example for asked question. It could relate with anonymous types which is (in my view, might be others can oppose) by design. Well explained in msdn:http://msdn.microsoft.com/en-us/library/bb397696.aspx – Gaurav Arora Feb 03 '14 at 20:03
  • There is a way to explain it simply. The runtime class of `p` is itself created on-the-fly as an anonymous inner class extending `Person`, with the given methods. If you use `getClass()` on your object, it won't return the `Person` class object, but a class with the name `Helloworld$1` (1st anonymous inner class of Helloworld). – Joffrey Jun 23 '15 at 12:08
-4

every body is writing dat abstract class has some virtual function which has not defined. for dat reason we cant create object, but abstract class is a class with the key word 'abstract' which may or may not have abstract method. i think it is a concept, it does not take any memory for dat. so if we can create an object den a memory will be created which is not possible, for dat reason we can't create object of an abstract class bt we can create reference of it which does not occupy any memory location.

  • Please use proper language, your post is annoying to read. That's probably why you got downvoted despite a content that could make sense. – Joffrey Jul 01 '15 at 21:09