There Are Two Type of Constructor in Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Types of Constructors

There are two type of constructor in Java:


1. No-argument constructor:
A constructor that has no parameter is known as default constructor.

42
If the constructor is not defined in a class, then compiler creates default con-structor
(with no arguments) for the class. If we write a constructor with ar-guments or no-argument
then compiler does not create default constructor. Default constructor provides the default
values to the object like 0, null etc. depending on the type.

// Java Program to illustrate calling a no-argument constructor


import java.io.*;
class myclass
{
int num;
String name;
// this would be invoked while object of that class
created. myclass()
{
System.out.println(“Constructor called”);
}
}
class myclassmain
{
public static void main (String[] args)
{
// this would invoke default constructor.
myclass m1 = new myclass();
// Default constructor provides the default values to the object like 0, null
System.out.println(m1.num);
System.out.println(m1.name);
}
}
2. Parameterized Constructor
A constructor that has parameters is known as parameterized constructor. If we want to
initialize fields of the class with your own values, then use parameterized constructor.

43
// Java Program to illustrate calling of parameterized constructor.
import java.io.*;
class myclass
{
// data members of the
class. String name;
int num;
// contructor with arguments.
myclass(String name, int n)
{
this.name = name;
this.num = n;
}
}
class myclassmain{
public static void main (String[] args)
{
// this would invoke parameterized constructor. myclass m1 =
new myclass(“Java”, 2017); System.out.println(“Name :” +
m1.name + “ num :” + m1.num);
}
}
There are no “return value” statements in constructor, but constructor returns current
class instance. We can write ‘return’ inside a constructor.
1.17 Constructor Overloading
Like methods, we can overload constructors for creating objects in different ways.
Compiler differentiates constructors on the basis of numbers of parameters, types of the
parameters and order of the parameters.

44
// Java Program to illustrate constructor overloading
import java.io.*;
class myclass
{
// constructor with one argument
myclass (String name)
{
System.out.println(“Constructor with one “ + “argument - String : “ + name);
}
// constructor with two arguments
myclass (String name, int id)
{
System.out.print(“Constructor with two arguments : “ +” String and Integer : “ + name
+ “ “+ id);
}
// Constructor with one argument but with different type than
previous. myclass (long num)
{
System.out.println(“Constructor with one argument : “ +”Long : “ + num);
}
}
class myclassmain
{
public static void main(String[] args)
{
myclass m1 = new myclass (“JAVA”);
myclass m2 = new myclass (“Python”, 2017);
myclass m3 = new myclass(3261567);
}
}

45
Constructors are different from methods in Java
• Constructor(s) must have the same name as the class within which it defined while
it is not necessary for the method in java.
• Constructor(s) do not any return type while method(s) have the return type or void
if does not return any value.
• Constructor is called only once at the time of Object creation while method(s) can
be called any numbers of time.

Creating an Object
The class provides the blueprints for objects. The objects are the instances of the class.
In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class −
• Declaration − A variable declaration with a variable name with an object type.
• Instantiation − The ‘new’ keyword is used to create the object.
• Initialization − The ‘new’ keyword is followed by a call to a constructor. This call
initializes the new object.

1.2 OOP Concepts In Java


OOP concepts in Java are the main ideas behind Java’s Object Oriented Programming.
They are:

4
Introduction to Oop and Java Fundamentals 1.5

Object
Any entity that has state and behavior is known as an object. It can be either physical or
logical.
For example: chair, pen, table, keyboard, bike etc.
Class & Instance
Collection of objects of the same kind is called class. It is a logical entity.
A Class is a 3-Compartment box encapsulating data and operations as shown in figure.

Class Name

Static Attributes

Dynamic Behaviors

Figure: Class Structure


The followings figure shows two classes ‘Student’ and ‘Circle’.

Name (Identifier) Student Circle


Variables (Static Attributes) name, gender, dept, marks radius, color
Methods getDetails() getRadius()
(Dynamic Behaviors) calculateGrade() printArea()
Figure: Examples of classes
A class can be visualized as a three-compartment box, as illustrated:
1. Name (or identity): identifies the class.
2. Variables (or attribute, state, field): contain the static attributes of the class.
3. Methods (or behaviors, function, operation): contain the dynamic behaviors of the
class.
An instance is an instantiation of a class. All the instances of a class have similar
proper-ties, as described in the class definition. The term “object” usually refers to instance.
For example, we can define a class called “Student” and create three instances of the
class “Student” for “John”, “Priya” and “Anil”.
The following figure shows three instances of the class Student, identified as “John”,
“Priya” and “Anil”.

5
1.6  Object Oriented Programming

John : Student Priya : Student Anil : Student


name = “John” name = “Priya” name = “Anil”
gender = “male” gender = “female” gender = “male”
dept = “CSE” gender = “female” gender = “male”
mark = 88 dept = “IT” dept = “IT”
getDetails() getDetails() getDetails()
calculateGrade() calculateGrade() calculateGrade()
Figure: Instances of a class ‘Student’

Abstraction
Abstraction refers to the quality of dealing with ideas rather than events. It basically
deals with hiding the details and showing the essential things to the user.
We all know how to turn the TV on, but we don’t need to know how it works in order to
enjoy it.
Abstraction means simple things like objects, classes, and variables represent more
com-plex underlying code and data. It avoids repeating the same work multiple times. In
java, we use abstract class and interface to achieve abstraction.
Abstract class:
Abstract class in Java contains the ‘abstract’ keyword. If a class is declared abstract, it
cannot be instantiated. So we cannot create an object of an abstract class. Also, an abstract
class can contain abstract as well as concrete methods.
To use an abstract class, we have to inherit it from another class where we have to
provide implementations for the abstract methods there itself, else it will also become an
abstract class.
Interface:
Interface in Java is a collection of abstract methods and static constants. In an interface,
each method is public and abstract but it does not contain any constructor. Along with ab-
straction, interface also helps to achieve multiple inheritance in Java.
So an interface is a group of related methods with empty bodies.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
It means to hide our data in order to make it safe from any modification.
The best way to understand encapsulation is to look at the example of a medical
capsule, where the drug is always safe inside the capsule. Similarly, through encapsulation
the meth-ods and variables of a class are well hidden and safe.

6
A java class is the example of encapsulation.
Encapsulation can be achieved in Java by:
• Declaring the variables of a class as private.
• Providing public setter and getter methods to modify and view the variables values.
Inheritance
This is a special feature of Object Oriented Programming in Java. It lets programmers
create new classes that share some of the attributes of existing classes.
For eg, a child inherits the properties from his father.
Similarly, in Java, there are two classes:
1. Parent class (Super or Base class)
2. Child class (Subclass or Derived class)
A class which inherits the properties is known as ‘Child class’ whereas a class whose
properties are inherited is known as ‘Parent class’.
Inheritance is classified into 4 types:

Single Inheritance
It enables a derived class to inherit the properties and behavior from a single parent
class.

Here, Class A is a parent class and Class B is a child class which inherits the properties
and behavior of the parent class.

7
Multilevel Inheritance
When a class is derived from a class which is also derived from another class, i.e. a
class having more than one parent class but at different levels, such type of inheritance is
called Multilevel Inheritance.

Here, class B inherits the properties and behavior of class A and class C inherits the
prop-erties of class B. Class A is the parent class for B and class B is the parent class for C.
So, class C implicitly inherits the properties and methods of class A along with Class B.
Hierarchical Inheritance
When a class has more than one child class (sub class), then such kind of inheritance is
known as hierarchical inheritance.

Here, classes B and C are the child classes which are inheriting from the parent class A.
Hybrid Inheritance
Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance.
Since multiple inheritance is not supported in Java as it leads to ambiguity, this type of
inheri-tance can only be achieved through the use of the interfaces.

8
Here, class A is a parent class for classes B and C, whereas
classes B and C are the parent classes of D which is the only child
class of B and C.
Polymorphism
Polymorphism means taking many forms, where ‘poly’ means
many and ‘morph’ means forms. It is the ability of a variable,
function or object to take on multiple forms. In other words,
polymorphism allows us to define one interface or method and
have multiple imple-mentations.

For eg, Bank is a base class that provides a method rate of


interest. But, rate of interest may differ according to banks. For
example, SBI, ICICI and AXIS are the child classes that provide
different rates of interest.
Polymorphism in Java is of two types:
• Run time polymorphism
• Compile time polymorphism
Run time polymorphism:
In Java, runtime polymorphism refers to a process in which a
call to an overridden method is resolved at runtime rather than at
compile-time. Method overriding is an example of run time
polymorphism.
Compile time polymorphism:
In Java, compile time polymorphism refers to a process in
which a call to an overloaded method is resolved at compile time
rather than at run time. Method overloading is an example of
compile time polymorphism.

You might also like