Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can an abstract class have constructor? [duplicate]

Tags:

Why does an abstract class have constructor? What's the point? It's obvious that we cannot create an instance of an abstract class.

like image 319
Aslam Jiffry Avatar asked Nov 13 '13 03:11

Aslam Jiffry


People also ask

Can abstract class have copy constructor?

Yes you should. Rules of having your own implementations for copy constructor, copy assignment operator and destructor for a Class will apply to even an Abstract Class.

Why does an abstract class have a constructor?

The main purpose of the constructor is to initialize the newly created object. In abstract class, we have an instance variable, abstract methods, and non-abstract methods. We need to initialize the non-abstract methods and instance variables, therefore abstract classes have a constructor.

Why abstract class has constructor even though you Cannot create object?

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. abstract class has a protected constructor (by default) allowing derived types to initialize it.

Can abstract class have multiple constructor?

Yes, an abstract class can have a constructor in Java. You can either explicitly provide a constructor to the abstract class or if you don't, the compiler will add a default constructor of no argument in the abstract class. This is true for all classes and it also applies to an abstract class.


1 Answers

One important reason is due to the fact there's an implicit call to the base constructor prior to the derived constructor execution. Keep in mind that unlike interfaces, abstract classes do contain implementation. That implementation may require field initialization or other instance members. Note the following example and the output:

   abstract class Animal    {        public string DefaultMessage { get; set; }         public Animal()        {            Console.WriteLine("Animal constructor called");            DefaultMessage = "Default Speak";        }        public virtual void Speak()        {            Console.WriteLine(DefaultMessage);        }    }      class Dog : Animal     {         public Dog(): base()//base() redundant.  There's an implicit call to base here.         {             Console.WriteLine("Dog constructor called");         }         public override void Speak()         {             Console.WriteLine("Custom Speak");//append new behavior             base.Speak();//Re-use base behavior too         }     } 

Although we cannot directly construct an Animal with new, the constructor is implicitly called when we construct a Dog.

OUTPUT:
Animal constructor called
Dog constructor called
Custom Speak
Default Speak

like image 109
P.Brian.Mackey Avatar answered Sep 18 '22 20:09

P.Brian.Mackey