Constructors in Java
Constructors in Java
Constructor is a block of code that initializes the newly created object. A constructor resembles an instance method in java
but it’s not a method as it doesn’t have a return type. In short constructor and method are different(More on this at the
end of this guide). People often refer constructor as special type of method in Java.
Constructor has same name as the class and looks like this in a java code.
public class MyClass{
//This is the constructor
MyClass(){
}
..
}
Simple program to display use of constructor
public class Hello {
String name;
//Constructor
Hello(){
this.name = "BeginnersBook.com";
}
public static void main(String[] args) {
Hello obj = new Hello();
System.out.println(obj.name);
}
}
Output:
BeginnersBook.com
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the
time of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. 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.
Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a
constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
Note: We can use access modifiers while declaring a constructor. It controls the object creation. In other words, we can
have private, protected, public or default constructor in Java.
Types of Java constructors
There are two types of constructors in Java:
Default constructor (no-arg constructor)
Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output :
30
60
31.0
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
Output:
Maximum Speed: 120
In the above example, both base class and subclass have a member maxSpeed. We could access maxSpeed of base class
in subclass using super keyword.
2. Use of super with methods: This is used when we want to call parent class method. So whenever a parent and child
class have same named methods then to resolve ambiguity we use super keyword. This code snippet helps to
understand the said usage of super keyword.
filter_none
edit
play_arrow
brightness_4
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
Output:
This is student class
This is person class
In the above example, we have seen that if we only call method message() then, the current class message() is invoked
but with the use of super keyword, message() of superclass could also be invoked.
3. Use of super with constructors: super keyword can also be used to access the parent class constructor. One more
important thing is that, ‘’super’ can call both parametric as well as non parametric constructors depending upon the
situation. Following is the code snippet to explain the above concept:
filter_none
edit
play_arrow
brightness_4
/* superclass Person */
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
Output:
Person class Constructor
Student class Constructor
In the above example we have called the superclass constructor using keyword ‘super’ via subclass constructor.
Other Important points:
Call to super() must be first statement in Derived(Student) Class constructor.
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the
no-argument constructor of the superclass. If the superclass does not have a no-argument constructor, you will get a
compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
If a subclass constructor invokes a constructor of its superclass, either explicitly or implicitly, you might think that a
whole chain of constructors called, all the way back to the constructor of Object. This, in fact, is the case. It is
called constructor chaining..
What is Aggregation in java?
Aggregation is a special form of association. It is a relationship between two classes like association, however its
a directional association, which means it is strictly a one way association. It represents a HAS-A relationship.
Aggregation Example in Java
class Operation{
int square(int n){
return n*n;
}
}
class Circle{
Operation op;//aggregation
double pi=3.14;
class One {
public void methodOne()
{
// Some Functionality
}
}
Implements: In Java, the implements keyword is used to implement an interface. An interface is a special type of class
which implements a complete abstraction and only contains abstract methods. To access the interface methods, the
interface must be “implemented” by another class with the implements keyword and the methods need to be
implemented in the class which is inheriting the properties of the interface. Since an interface is not having the
implementation of the methods, a class can implement any number of interfaces at a time.
Example
filter_none
brightness_4
// Defining an interface
interface One {
public void methodOne();
}
Note: A class can extend a class and can implement any number of interfaces simultaneously.
Example
filter_none
brightness_4
// Abstract method
void methodOne();
}
// Defining a class
class Two {
// Defining a method
public void methodTwo()
{
}
}
The following table explains the difference between the extends and interface:
S.No
. Extends Implements
It is not compulsory that subclass that extends a It is compulsory that class implementing an interface
2. superclass override all the methods in a superclass. has to implement all the methods of that interface.
Inheritance in Java
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java by which one class
is allow to inherit the features(fields and methods) of another class.
Important terminology:
Super Class: The class whose features are inherited is known as super class(or a base class or a parent class).
Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended class, or child class).
The subclass can add its own fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is
already a class that includes some of the code that we want, we can derive our new class from the existing class. By
doing this, we are reusing the fields and methods of the existing class.
How to use inheritance in Java
The keyword used for inheritance is extends.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Example: In below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class which
extends Bicycle class and class Test is a driver class to run program.
// base class
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;
// derived class
class MountainBike extends Bicycle
{
// driver class
public class Test
{
public static void main(String args[])
{
}
}
Output:
No of gears are 3
speed of bicycle is 100
seat height is 25
In above program, when an object of MountainBike class is created, a copy of the all methods and fields of the
superclass acquire memory in this object. That is why, by using the object of the subclass we can also access the
members of a superclass.
Please note that during inheritance only object of subclass is created, not the superclass. For more, refer Java Object
Creation of Inherited Class .
In practice, inheritance and polymorphism are used together in java to achieve fast performance and readability of code.
Types of Inheritance in Java
Below are the different types of inheritance which is supported by Java.
Single Inheritance : In single inheritance, subclasses inherit the features of one superclass. In image below, the class A
serves as a base class for the derived class B.
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
Output:
Geeks
for
Geeks
Multilevel Inheritance : In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the derived
class also act as the base class to other class. In below image, the class A serves as a base class for the derived class B,
which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s
members.
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks
Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one sub
class.In below image, the class A serves as a base class for the derived class B,C and D.
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
two t = new two();
t.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks
Multiple Inheritance (Through Interfaces) : In Multiple inheritance ,one class can have more than one superclass and
inherit features from all parent classes. Please note that Java does not support multiple inheritance with classes. In java,
we can achieve multiple inheritance only through Interfaces. In image below, Class C is derived from interface A and B.
interface one
{
public void print_geek();
}
interface two
{
public void print_for();
}
// Drived class
public class Main
{
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}
Output:
Geeks
for
Geeks
Hybrid Inheritance(Through Interfaces) : It is a mix of two or more of the above types of inheritance. Since java doesn’t
support multiple inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can achieve
hybrid inheritance only through Interfaces.