Why does an abstract class have constructor? What's the point? It's obvious that we cannot create an instance of an abstract class.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With