Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructors and inheritance in Java

I have a question about default constructors and inheritance in Java.

Generally, if you write a class and do not include any constructor, Java provides automatically for you a default constructor (one without parameters), which initializes all instance variables of the class (if there are any) with some default values (0, null, or false). If you write a constructor, however, with some parameters, and you don't write any default constructor, then Java does not provide a default constructor. My question is: what is the case with classes, which inherit from other classes - if I write a constructor with some parameters in them, but don't include a default constructor, do they inherit the default constructor of the super class?

like image 417
user42155 Avatar asked Feb 08 '09 11:02

user42155


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 inheritance in Java?

In java, by default, the Object class is the parent class. In Java inheritance is declared using the extends keyword. You declare that one class extends another class by using the extends keyword in the class definition.

What is constructor inheritance in Java?

No, constructors cannot be inherited in Java. In inheritance sub class inherits the members of a super class except constructors. In other words, constructors cannot be inherited in Java therefore, there is no need to write final before constructors.

What is constructor and default constructor in Java?

The constructors have same name as their class and, have no return type. The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc.


1 Answers

  1. If you do not make a constructor, the default empty constructor is automatically created.

  2. If any constructor does not explicitly call a super or this constructor as its first statement, a call to super() is automatically added.

Always.

like image 62
paulmurray Avatar answered Oct 14 '22 15:10

paulmurray