Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructors in Java

I know I'm asking some serious 101 question here...

I have some class Foo and a class Bar that extends Foo. In Foo I have a constructor that takes a set of parameters that it sets to its fields. Deriving classes such as Bar will typically not need to modify this. Now my IDE is giving me "There is no default constructor available in Foo". From a bit of Googling this appears to be because "constructors are not inherited". So all nice and well, but how do I now get this to work without duplicating this constructor in every deriving class? I'm assuming there is a more sane approach?

like image 551
Jeroen De Dauw Avatar asked Jun 12 '13 14:06

Jeroen De Dauw


People also ask

What are default constructors in Java?

What is a default constructor? A default constructor is a constructor created by the compiler if we do not define any constructor(s) for a class. Here is an example: public class Student { String firstName; String lastName; int age; public static void main(String args[]) { Student myStudent = new Student(); myStudent.

What is default constructor?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

How many default constructors are there in Java?

In such case, Java compiler provides a default constructor by default. There are two types of constructors in Java: no-arg constructor, and parameterized constructor.


1 Answers

Use the super constructor:

public Bar(int a, double b, ...) {     super(a, b, ...); } 
like image 142
arshajii Avatar answered Sep 23 '22 01:09

arshajii