0% found this document useful (0 votes)
32 views14 pages

Constructors in Java

Constructor is a special type of method that initializes an object when it is created. It has the same name as the class and does not have a return type. There are two types of constructors: default (no-arg) constructor and parameterized constructor. The constructor is called automatically when an object is created using the new keyword and allocates memory for the object.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
32 views14 pages

Constructors in Java

Constructor is a special type of method that initializes an object when it is created. It has the same name as the class and does not have a return type. There are two types of constructors: default (no-arg) constructor and parameterized constructor. The constructor is called automatically when an object is created using the new keyword and allocates memory for the object.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 14

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

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same
values also.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can have any number of
parameters in the constructor.
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
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.
Example of Constructor Overloading
//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25
this keyword in java
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke current class constructor.
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this can be used to return the current class instance from the method.

// Java program to demonstrate working of method


// overloading in Java.

public class Sum {

// Overloaded sum(). This sum takes two int parameters


public int sum(int x, int y)
{
return (x + y);
}

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double parameters


public double sum(double x, double y)
{
return (x + y);
}

// 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

Super Keyword in Java


The super keyword in java is a reference variable that is used to refer parent class objects. The keyword “super” came
into the picture with the concept of Inheritance. It is majorly used in the following contexts:
1. Use of super with variables: This scenario occurs when a derived class and base class has same data members. In that
case there is a possibility of ambiguity for the JVM. We can understand it more clearly using this code snippet:

/* Base class vehicle */


class Vehicle
{
int maxSpeed = 120;
}

/* sub class Car extending vehicle */


class Car extends Vehicle
{
int maxSpeed = 180;

void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}

/* Driver program to test */


class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

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

/* Base class Person */


class Person
{
void message()
{
System.out.println("This is person class");
}
}

/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}

// Note that display() is only in Student class


void display()
{
// will invoke or call current class message() method
message();

// will invoke or call parent class message() method


super.message();
}
}

/* Driver program to test */


class Test
{
public static void main(String args[])
{
Student s = new Student();

// calling display() of Student


s.display();
}
}

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");
}
}

/* subclass Student extending the Person class */


class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();

System.out.println("Student class Constructor");


}
}
/* Driver program to test*/
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}

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;

double area(int radius){


op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}

public static void main(String args[]){


Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}
Test it Now
Output:78.5
Extends vs Implements in Java
Inheritance is an important pillar of OOP(Object Oriented Programming) . It is the mechanism in Java by which one class
is allowed to inherit the features(fields and methods) of another class. There are two main
keywords, “extends” and “implements” which are used in Java for inheritance. In this article, the difference between
extends and implements is discussed.
Before getting into the differences, lets first understand in what scenarios each of the keywords are used.
Extends: In Java, the extends keyword is used to indicate that the class which is being defined is derived from the base
class using inheritance. So basically, extends keyword is used to extend the functionality of the parent class to the
subclass. In Java, multiple inheritances are not allowed due to ambiguity. Therefore, a class can extend only one class to
avoid ambiguity.
Example:
filter_none
brightness_4

class One {
public void methodOne()
{

// Some Functionality
}
}

class Two extends One {

public static void main(String args[])


{
Two t = new Two();

// Calls the method one


// of the above class
t.methodOne();
}
}

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();
}

// Defining the second interface


interface Two {
public void methodTwo();
}

// Implementing the two interfaces


class Three implements One, Two {
public void methodOne()
{

// Implementation of the method


}

public void methodTwo()


{

// Implementation of the method


}
}

Note: A class can extend a class and can implement any number of interfaces simultaneously.
Example
filter_none
brightness_4

// Defining the interface


interface One {

// Abstract method
void methodOne();
}

// Defining a class
class Two {

// Defining a method
public void methodTwo()
{
}
}

// Class which extends the class Two


// and implements the interface One
class Three extends Two implements One {

public void methodOne()


{

// Implementation of the method


}
}

Note: An interface can extend any number of interfaces at a time.


Example:
filter_none
brightness_4

// Defining the interface One


interface One {
void methodOne();
}

// Defining the interface Two


interface Two {
void methodTwo();
}

// Interface extending both the


// defined interfaces
interface Three extends One, Two {
}

The following table explains the difference between the extends and interface:
S.No
. Extends Implements

By using “extends” keyword a class can inherit


another class, or an interface can inherit other By using “implements” keyword a class can
1. interfaces implement an 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.

A class can implement any number of an interface at


3. Only one superclass can be extended by a class. a time

Any number of interfaces can be extended by


4. interface. An interface can never implement any other 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.

//Java program to illustrate the


// concept of inheritance

// base class
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;

// the Bicycle class has one constructor


public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}

// the Bicycle class has three methods


public void applyBrake(int decrement)
{
speed -= decrement;
}

public void speedUp(int increment)


{
speed += increment;
}

// toString() method to print info of Bicycle


public String toString()
{
return("No of gears are "+gear
+"\n"
+ "speed of bicycle is "+speed);
}
}

// derived class
class MountainBike extends Bicycle
{

// the MountainBike subclass adds one more field


public int seatHeight;

// the MountainBike subclass has one constructor


public MountainBike(int gear,int speed,
int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}

// the MountainBike subclass adds one more method


public void setHeight(int newValue)
{
seatHeight = newValue;
}

// overriding toString() method


// of Bicycle to print more info
@Override
public String toString()
{
return (super.toString()+
"\nseat height is "+seatHeight);
}

// driver class
public class Test
{
public static void main(String args[])
{

MountainBike mb = new MountainBike(3, 100, 25);


System.out.println(mb.toString());

}
}

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.

//Java program to illustrate the


// concept of single inheritance
import java.util.*;
import java.lang.*;
import java.io.*;

class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one


{
public void print_for()
{
System.out.println("for");
}
}
// Driver class
public class Main
{
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

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.

// Java program to illustrate the


// concept of Multilevel inheritance
import java.util.*;
import java.lang.*;
import java.io.*;

class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one


{
public void print_for()
{
System.out.println("for");
}
}

class three extends two


{
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.

// Java program to illustrate the


// concept of Hierarchical inheritance
import java.util.*;
import java.lang.*;
import java.io.*;

class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one


{
public void print_for()
{
System.out.println("for");
}
}

class three extends one


{
/*............*/
}

// 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.

// Java program to illustrate the


// concept of Multiple inheritance
import java.util.*;
import java.lang.*;
import java.io.*;

interface one
{
public void print_geek();
}

interface two
{
public void print_for();
}

interface three extends one,two


{
public void print_geek();
}
class child implements three
{
@Override
public void print_geek() {
System.out.println("Geeks");
}

public void print_for()


{
System.out.println("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.

Important facts about inheritance in Java


Default superclass: Except Object class, which has no superclass, every class has one and only one direct superclass
(single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object class.
Superclass can only be one: A superclass can have any number of subclasses. But a subclass can have
only one superclass. This is because Java does not support multiple inheritance with classes. Although with interfaces,
multiple inheritance is supported by java.
Inheriting Constructors: A subclass inherits all the members (fields, methods, and nested classes) from its superclass.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be
invoked from the subclass.
Private member inheritance: A subclass does not inherit the private members of its parent class. However, if the
superclass has public or protected methods(like getters and setters) for accessing its private fields, these can also be
used by the subclass.

You might also like