Module 3 Constructor and Inheritance
Module 3 Constructor and Inheritance
Example
The following Java program demonstrates the creation of constructors.
Output
Name of the Student: Raju
Age of the Student: 20
Output:
Bike is created
Note:
• if there is no constructor in a class, compiler automatically creates a default constructor.
• The default constructor is used to provide the default value to the object like 0, null, etc…,
depending on the type.
Output
111 Karan
222 Aryan
Constructor Overloading
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list and their types.
Output
111 Karan 0
222 Aryan 25
Module 3 - Java Constructor and Inheritance
A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor if you The method is not provided by the
don't have any constructor in a class. compiler in any case.
The constructor name must be same as the class name. The method name may or may not be
same as the class name.
Module 3 - Java Constructor and Inheritance
Output
111 Karan
111 Karan
Java Inheritance
In Java, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:
In the example below, the Car class (subclass) inherits the attributes and methods from
the Vehicle class (superclass):
Resources
• https://techvidvan.com/tutorials/java-
constructor/#:~:text=Rules%20for%20Writing%20Constructors%20in%20Java,-
Following%20are%20some&text=The%20name%20of%20the%20constructor%20must%20be
%20the%20same%20as,classes%20can%20call%20the%20constructor.
• https://www.tutorialspoint.com/what-are-the-rules-to-create-a-constructor-in-java
• https://www.javatpoint.com/java-constructor
Tutorial:
Inheritance: https://www.youtube.com/watch?v=ptyqpfyB6oA
Constructor: https://www.youtube.com/watch?v=zoZ8uzpDiBA