Constructor in java is a special type of method that is used to
initialize the object.
Java constructor is invoked at
the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
Rules
for creating java constructor
There are basically two rules
defined for the constructor.
- Constructor name must be same as its class name
- Constructor must have no explicit return type
Types
of java constructors
There are two types of constructors:
- Default constructor (no-arg constructor)
- Parameterized constructor

Java
Default Constructor
A constructor that have no
parameter is known as default constructor.
|
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.
|
- class Bike1{
- Bike1()
- {
- System.out.println("Bike is created");}
- public static void main(String args[]){
- Bike1 b=new Bike1();
- }
- }
Output:
Bike
is created
Rule:
If there is no constructor in a class, compiler automatically creates a default
constructor.

Q)
What is the purpose of default constructor?
Default constructor provides the
default values to the object like 0, null etc. depending on the type.
Example
of default constructor that displays the default values
- class Student3{
- int id;
- String name;
-
- void display(){System.out.println(id+" "+name);}
-
- public static void main(String args[]){
- Student3 s1=new Student3();
- Student3 s2=new Student3();
- s1.display();
- s2.display();
- }
- }
Output:
0
null
0
null
Explanation:In the above class,you are not creating any constructor so
compiler provides you a default constructor.Here 0 and null values are provided
by default constructor.
Java
parameterized constructor
A constructor that have parameters
is known as parameterized constructor.
|
Why
use parameterized constructor?
Parameterized constructor is used
to provide different values to the distinct objects.
|
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.
|
- class Student4{
- int id;
- String name;
-
- Student4(int i,String n){
- id = i;
- name = n;
- }
- void display(){System.out.println(id+" "+name);}
-
- public static void main(String args[]){
- Student4 s1 = new Student4(111,"Karan");
- Student4 s2 = new Student4(222,"Aryan");
- s1.display();
- s2.display();
- }
- }
Output:
111
Karan
222
Aryan
Constructor
Overloading in Java
Constructor overloading is a
technique in Java in which a class can have any number of constructors that
differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
|
Example
of Constructor Overloading
- class Student5{
- int id;
- String name;
- int age;
- Student5(int i,String n){
- id = i;
- name = n;
- }
- 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
Difference
between constructor and method in java
There are many differences between constructors
and methods. They are given below.
Java
Constructor
|
Java
Method
|
Constructor is used to initialize
the state of an object.
|
Method is used to expose behaviour
of an object.
|
Constructor must not have return
type.
|
Method must have return type.
|
Constructor is invoked implicitly.
|
Method is invoked explicitly.
|
The java compiler provides a
default constructor if you don't have any constructor.
|
Method is not provided by compiler
in any case.
|
Constructor name must be same as
the class name.
|
Method name may or may not be same
as class name.
|
Method Overloading in Java
If a class have multiple methods by
same name but different parameters, it is known as Method Overloading.
If we have to perform only one
operation, having same name of the methods increases the readability of the
program.
Suppose you have to perform addition
of the given numbers but there can be any number of arguments, if you write the
method such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you as well as other programmers to
understand the behaviour of the method because its name differs. So, we perform
method overloading to figure out the program quickly.
Advantage
of method overloading?
Method overloading increases the
readability of the program.
Different
ways to overload the method
There are two ways to overload the
method in java
|
|
In
java, Methood Overloading is not possible by changing the return type of the
method.
1)Example
of Method Overloading by changing the no. of arguments
In this example, we have created two
overloaded methods, first sum method performs addition of two numbers and
second sum method performs addition of three numbers.
- class Calculation{
- void sum(int a,int b){System.out.println(a+b);}
- void sum(int a,int b,int c){System.out.println(a+b+c);}
-
- public static void main(String args[]){
- Calculation obj=new Calculation();
- obj.sum(10,10,10);
- obj.sum(20,20);
-
- }
- }
Output:30
40
2)Example
of Method Overloading by changing data type of argument
In this example, we have created two
overloaded methods that differs in data type. The first sum method receives two
integer arguments and second sum method receives two double arguments.
- class Calculation2{
- void sum(int a,int b){System.out.println(a+b);}
- void sum(double a,double b){System.out.println(a+b);}
-
- public static void main(String args[]){
- Calculation2 obj=new Calculation2();
- obj.sum(10.5,10.5);
- obj.sum(20,20);
-
- }
- }
Output:21.0
40
Method Overriding in Java
Methods
having the same name with same parameters but in different classes is referred
as method overriding.
If subclass (child class) has the
same method as declared in the parent class, it is known as method
overriding in java.
In other words, If subclass provides
the specific implementation of the method that has been provided by one of its
parent class, it is known as method overriding.
Usage
of Java Method Overriding
- Method overriding is used to provide specific
implementation of a method that is already provided by its super class.
- Method overriding is used for runtime polymorphism
Rules
for Java Method Overriding
- method must have same name as in the parent class
- method must have same parameter as in the parent class.
- must be IS-A relationship (inheritance).
Understanding
the problem without method overriding
Let's understand the problem that we
may face in the program if we don't use method overriding.
- class Vehicle{
- void run(){System.out.println("Vehicle is running");}
- }
- class Bike extends Vehicle{
-
- public static void main(String args[]){
- Bike obj = new Bike();
- obj.run();
- }
- }
Output:Vehicle
is running
Problem is that I have to provide a
specific implementation of run() method in subclass that is why we use method
overriding.
Example
of method overriding
In this example, we have defined the
run method in the subclass as defined in the parent class but it has some
specific implementation. The name and parameter of the method is same and there
is IS-A relationship between the classes, so there is method overriding.
- class Vehicle{
- void run(){System.out.println("Vehicle is running");}
- }
- class Bike2 extends Vehicle{
- void run(){System.out.println("Bike is running safely");}
-
- public static void main(String args[]){
- Bike2 obj = new Bike2();
- obj.run();
- }
Output:Bike
is running safely
Real
example of Java Method Overriding
Consider a scenario, Bank is a class
that provides functionality to get rate of interest. But, rate of interest
varies according to banks. For example, SBI, ICICI and AXIS banks could provide
8%, 7% and 9% rate of interest.

- class Bank{
- int getRateOfInterest(){return 0;}
- }
-
- class SBI extends Bank{
- int getRateOfInterest(){return 8;}
- }
-
- class ICICI extends Bank{
- int getRateOfInterest(){return 7;}
- }
- class AXIS extends Bank{
- int getRateOfInterest(){return 9;}
- }
-
- class Test2{
- public static void main(String args[]){
- SBI s=new SBI();
- ICICI i=new ICICI();
- AXIS a=new AXIS();
- System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
- System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
- System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
- }
- }
Output:
SBI
Rate of Interest: 8
ICICI
Rate of Interest: 7
AXIS Rate of Interest:
9
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object.
The idea behind inheritance in java is
that you can create new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and fields of parent
class, and you can add new methods and fields also.
Inheritance represents the IS-A
relationship, also known as parent-child relationship.
Why
use inheritance in java
- For Method Overriding (so runtime polymorphism can be
achieved).
- For Code Reusability.
Syntax
of Java Inheritance
- class Subclass-name extends Superclass-name
- {
- //methods and fields
- }
The extends keyword indicates
that you are making a new class that derives from an existing class.
In the terminology of Java, a class
that is inherited is called a super class. The new class is called a subclass.
Understanding
the simple example of inheritance

As displayed in the above figure,
Programmer is the subclass and Employee is the superclass. Relationship between
two classes is Programmer IS-A Employee.It means that Programmer is a
type of Employee.
- class Employee{
- float salary=40000;
- }
- class Programmer extends Employee{
- int bonus=10000;
- public static void main(String args[]){
- Programmer p=new Programmer();
- System.out.println("Programmer salary is:"+p.salary);
- System.out.println("Bonus of Programmer is:"+p.bonus);
- }
- }
Programmer
salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer
object can access the field of own class as well as of Employee class i.e. code
reusability.
Types
of inheritance in java
On the basis of class, there can be
three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and
hybrid inheritance is supported through interface only. We will learn about
interfaces later.

Note:
Multiple inheritance is not supported in java through class.
When a class extends multiple
classes i.e. known as multiple inheritance. For Example:

Q)
Why multiple inheritance is not supported in java?
To reduce the complexity and
simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C
are three classes. The C class inherits A and B classes. If A and B classes
have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.
Since compile time errors are better
than runtime errors, java renders compile time error if you inherit 2 classes.
So whether you have same method or different, there will be compile time error
now.
- class A{
- void msg(){System.out.println("Hello");}
- }
- class B{
- void msg(){System.out.println("Welcome");}
- }
- class C extends A,B{//suppose if it were
-
- Public Static void main(String args[]){
- C obj=new C();
- obj.msg();//Now which msg() method would be invoked?
- }
- }
Compile Time Error
Access Modifiers in java
- private
access modifier
- Role
of private constructor
- default
access modifier
- protected
access modifier
- public
access modifier
- Applying
access modifier with method overriding
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
- private
- default
- protected
- public
1) private access modifier
The private access modifier is accessible only within
class.
|
Simple example of private access modifier
In this example, we have created two classes A and Simple.
A class contains private data member and private method. We are accessing
these private members from outside the class, so there is compile time error.
|
- class A{
- private int data=40;
- private void msg(){System.out.println("Hello java");}
- }
-
- public class Simple{
- public static void main(String args[]){
- A obj=new A();
- System.out.println(obj.data);//Compile Time Error
- obj.msg();//Compile Time Error
- }
- }
Role of Private Constructor
If you make any class constructor private, you cannot
create the instance of that class from outside the class. For example:
|
- class A{
- private A(){}//private constructor
- void msg(){System.out.println("Hello java");}
- }
- public class Simple{
- public static void main(String args[]){
- A obj=new A();//Compile Time Error
- }
- }
Note: A class cannot be private or protected except nested class.
2) default access modifier
If you don't use any modifier, it is treated as default
bydefault. The default modifier is accessible only within package.
|
Example of default access modifier
In this example, we have created two packages pack and
mypack. We are accessing the A class from outside its package, since A class
is not public, so it cannot be accessed from outside the package.
|
- //save by A.java
- package pack;
- class A{
- void msg(){System.out.println("Hello");}
- }
- //save by B.java
- package mypack;
- import pack.*;
- class B{
- public static void main(String args[]){
- A obj = new A();//Compile Time Error
- obj.msg();//Compile Time Error
- }
- }
3) protected access modifier
The protected access modifier is accessible within package and
outside the package but through inheritance only. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A
class of pack package is public, so can be accessed from outside the package.
But msg method of this package is declared as protected, so it can be accessed
from outside the class only through inheritance.- //save by A.java
- package pack;
- public class A{
- protected void msg(){System.out.println("Hello");}
- }
- //save by B.java
- package mypack;
- import pack.*;
-
- class B extends A{
- public static void main(String args[]){
- B obj = new B();
- obj.msg();
- }
- }
Output:Hello
4) public access modifier
The public access modifier is accessible
everywhere. It has the widest scope among all other modifiers.
|
Example of public access modifier
- //save by A.java
-
- package pack;
- public class A{
- public void msg(){System.out.println("Hello");}
- }
- //save by B.java
-
- package mypack;
- import pack.*;
-
- class B{
- public static void main(String args[]){
- A obj = new A();
- obj.msg();
- }
- }
Output:Hello
Understanding all java access modifiers
Let's understand the access modifiers by a simple table.
Access Modifier
|
within class
|
within package
|
outside package
by subclass only
|
outside package
|
Private
|
Y
|
N
|
N
|
N
|
Default
|
Y
|
Y
|
N
|
N
|
Protected
|
Y
|
Y
|
Y
|
N
|
Public
|
Y
|
Y
|
Y
|
Y
|
Java access modifiers with method overriding
If you are overriding any method, overridden method (i.e. declared in
subclass) must not be more restrictive.- class A{
- protected void msg(){System.out.println("Hello java");}
- }
-
- public class Simple extends A{
- void msg(){System.out.println("Hello java");}//C.T.Error
- public static void main(String args[]){
- Simple obj=new Simple();
- obj.msg();
- }
- }
The default modifier is more restrictive than protected.
That is why there is compile time error.
|
0 Comments