Why do abstract classes in Java have constructors?

Why does the abstract class in Java have a constructor ?

What is it because we cannot create an instance of the abstract class?

Any thoughts?

+55
java constructor abstract-class
Jan 31 '10 at 3:56
source share
7 answers

A constructor in Java does not actually β€œbuild” an object; it is used to initialize fields.

Imagine that your abstract class has fields x and y and that you always want them to be initialized in a certain way, no matter what specific concrete subclass will ultimately be created. Thus, you create a constructor and initialize these fields.

Now, if you have two different subclasses of your abstract class, when you create them, their calls will be called, and then the parent constructor will be called and the fields will be initialized.

If you do nothing, the default constructor of the parent will be called. However, you can use the super keyword to invoke the specific constructor of the parent class.

+76
Jan 31 '10 at 4:02
source share

All classes, including abstract classes, can have constructors. Class constructor constructors will be called when a particular subclass is created.

+10
Jan 31 '10 at 4:01
source share

Two reasons for this:

1) Abstract classes have constructors , and these constructors are always called when a particular subclass is created. We know that when we are going to instantiate a class, we always use the constructor of this class. Now each constructor calls the constructor of its superclass with an implicit call to super() .

2) We know that the constructor is also used to initialize the fields of the class. We also know that abstract classes can contain fields, and sometimes they need to be initialized somehow using the constructor .

+9
Mar 05 2018-12-12T00:
source share

Since another class can extend it, and the child class needs to call the constructor of the superclass.

+7
Jan 31 '10 at 3:58
source share

Since abstract classes have state (fields), and something like this needs to be initialized somehow.

+4
Jan 31 '10 at 13:36
source share

I believe the root of this question is that people believe that calling the constructor creates an object. This is not relevant. Java does not claim anywhere that calling a constructor creates an object. It just does what we want the constructor to do, for example, initialize some fields. Thus, the called abstract class constructor does not mean that its object is created.

+2
Jun 02 '13 at 7:18
source share

You often see the implementation of the wise inside the super () operator in subclass constructors, something like:

 public class A extends AbstractB{ public A(...){ super(String constructorArgForB, ...); ... } }
public class A extends AbstractB{ public A(...){ super(String constructorArgForB, ...); ... } } 
+1
Jan 31 '10 at 10:21
source share



All Articles