Constructor in Java


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.

JAVA


Rules for creating java constructor
There are basically two rules defined for the constructor.
  1. Constructor name must be same as its class name
  2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
  1. Default constructor (no-arg constructor)
  2. Parameterized constructor
java constructor


Java Default Constructor
A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
  1. <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.
  1. class Bike1{  
  2. Bike1()
  3. {
  4. System.out.println("Bike is created");}  
  5. public static void main(String args[]){  
  6. Bike1 b=new Bike1();  
  7. }  
  8. }  
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
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
  1. class Student3{  
  2. int id;  
  3. String name;  
  4.   
  5. void display(){System.out.println(id+" "+name);}  
  6.   
  7. public static void main(String args[]){  
  8. Student3 s1=new Student3();  
  9. Student3 s2=new Student3();  
  10. s1.display();  
  11. s2.display();  
  12. }  
  13. }  
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.
  1. class Student4{  
  2.     int id;  
  3.     String name;  
  4.       
  5.     Student4(int i,String n){  
  6.     id = i;  
  7.     name = n;  
  8.     }  
  9.     void display(){System.out.println(id+" "+name);}  
  10.    
  11.     public static void main(String args[]){  
  12.     Student4 s1 = new Student4(111,"Karan");  
  13.     Student4 s2 = new Student4(222,"Aryan");  
  14.     s1.display();  
  15.     s2.display();  
  16.    }  
  17. }  
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
  1. class Student5{  
  2.     int id;  
  3.     String name;  
  4.     int age;  
  5.     Student5(int i,String n){  
  6.     id = i;  
  7.     name = n;  
  8.     }  
  9.     Student5(int i,String n,int a){  
  10.     id = i;  
  11.     name = n;  
  12.     age=a;  
  13.     }  
  14.     void display(){System.out.println(id+" "+name+" "+age);}  
  15.    
  16.     public static void main(String args[]){  
  17.     Student5 s1 = new Student5(111,"Karan");  
  18.     Student5 s2 = new Student5(222,"Aryan",25);  
  19.     s1.display();  
  20.     s2.display();  
  21.    }  
  22. }  
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

  1. By changing number of arguments
  2. By changing the data type
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.
  1. class Calculation{  
  2.   void sum(int a,int b){System.out.println(a+b);}  
  3.   void sum(int a,int b,int c){System.out.println(a+b+c);}  
  4.   
  5.   public static void main(String args[]){  
  6.   Calculation obj=new Calculation();  
  7.   obj.sum(10,10,10);  
  8.   obj.sum(20,20);  
  9.   
  10.   }  
  11. }  
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.
  1. class Calculation2{  
  2.   void sum(int a,int b){System.out.println(a+b);}  
  3.   void sum(double a,double b){System.out.println(a+b);}  
  4.   
  5.   public static void main(String args[]){  
  6.   Calculation2 obj=new Calculation2();  
  7.   obj.sum(10.5,10.5);  
  8.   obj.sum(20,20);  
  9.   
  10.   }  
  11. }  
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
  1. method must have same name as in the parent class
  2. method must have same parameter as in the parent class.
  3. 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.
  1. class Vehicle{  
  2.   void run(){System.out.println("Vehicle is running");}  
  3. }  
  4. class Bike extends Vehicle{  
  5.     
  6.   public static void main(String args[]){  
  7.   Bike obj = new Bike();  
  8.   obj.run();  
  9.   }  
  10. }  
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.
  1. class Vehicle{  
  2. void run(){System.out.println("Vehicle is running");}  
  3. }  
  4. class Bike2 extends Vehicle{  
  5. void run(){System.out.println("Bike is running safely");}  
  6.   
  7. public static void main(String args[]){  
  8. Bike2 obj = new Bike2();  
  9. obj.run();  
  10. }  
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.
Java method overriding example of bank
  1. class Bank{  
  2. int getRateOfInterest(){return 0;}  
  3. }  
  4.   
  5. class SBI extends Bank{  
  6. int getRateOfInterest(){return 8;}  
  7. }  
  8.   
  9. class ICICI extends Bank{  
  10. int getRateOfInterest(){return 7;}  
  11. }  
  12. class AXIS extends Bank{  
  13. int getRateOfInterest(){return 9;}  
  14. }  
  15.   
  16. class Test2{  
  17. public static void main(String args[]){  
  18. SBI s=new SBI();  
  19. ICICI i=new ICICI();  
  20. AXIS a=new AXIS();  
  21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());  
  22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());  
  23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());  
  24. }  
  25. }  
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
  1. class Subclass-name extends Superclass-name  
  2. {  
  3.    //methods and fields  
  4. }  
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
inheritance in java
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.
  1. class Employee{  
  2.  float salary=40000;  
  3. }  
  4. class Programmer extends Employee{  
  5.  int bonus=10000;  
  6.  public static void main(String args[]){  
  7.    Programmer p=new Programmer();  
  8.    System.out.println("Programmer salary is:"+p.salary);  
  9.    System.out.println("Bonus of Programmer is:"+p.bonus);  
  10. }  
  11. }  
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.
types of inheritance in java
Note: Multiple inheritance is not supported in java through class.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
multiple inheritance in java


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.
  1. class A{  
  2. void msg(){System.out.println("Hello");}  
  3. }  
  4. class B{  
  5. void msg(){System.out.println("Welcome");}  
  6. }  
  7. class C extends A,B{//suppose if it were  
  8.    
  9.  Public Static void main(String args[]){  
  10.    C obj=new C();  
  11.    obj.msg();//Now which msg() method would be invoked?  
  12. }  
  13. }  

 Compile Time Error

Access Modifiers in java

  1. private access modifier
  2. Role of private constructor
  3. default access modifier
  4. protected access modifier
  5. public access modifier
  6. Applying access modifier with method overriding
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
  1. private
  2. default
  3. protected
  4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers.

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.
  1. class A{  
  2. private int data=40;  
  3. private void msg(){System.out.println("Hello java");}  
  4. }  
  5.   
  6. public class Simple{  
  7.  public static void main(String args[]){  
  8.    A obj=new A();  
  9.    System.out.println(obj.data);//Compile Time Error  
  10.    obj.msg();//Compile Time Error  
  11.    }  
  12. }  

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:
  1. class A{  
  2. private A(){}//private constructor  
  3. void msg(){System.out.println("Hello java");}  
  4. }  
  5. public class Simple{  
  6.  public static void main(String args[]){  
  7.    A obj=new A();//Compile Time Error  
  8.  }  
  9. }  

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.
  1. //save by A.java  
  2. package pack;  
  3. class A{  
  4.   void msg(){System.out.println("Hello");}  
  5. }  
  1. //save by B.java  
  2. package mypack;  
  3. import pack.*;  
  4. class B{  
  5.   public static void main(String args[]){  
  6.    A obj = new A();//Compile Time Error  
  7.    obj.msg();//Compile Time Error  
  8.   }  
  9. }  
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.

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.
  1. //save by A.java  
  2. package pack;  
  3. public class A{  
  4. protected void msg(){System.out.println("Hello");}  
  5. }  
  1. //save by B.java  
  2. package mypack;  
  3. import pack.*;  
  4.   
  5. class B extends A{  
  6.   public static void main(String args[]){  
  7.    B obj = new B();  
  8.    obj.msg();  
  9.   }  
  10. }  
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

  1. //save by A.java  
  2.   
  3. package pack;  
  4. public class A{  
  5. public void msg(){System.out.println("Hello");}  
  6. }  
  1. //save by B.java  
  2.   
  3. package mypack;  
  4. import pack.*;  
  5.   
  6. class B{  
  7.   public static void main(String args[]){  
  8.    A obj = new A();  
  9.    obj.msg();  
  10.   }  
  11. }  
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.
  1. class A{  
  2. protected void msg(){System.out.println("Hello java");}  
  3. }  
  4.   
  5. public class Simple extends A{  
  6. void msg(){System.out.println("Hello java");}//C.T.Error  
  7.  public static void main(String args[]){  
  8.    Simple obj=new Simple();  
  9.    obj.msg();  
  10.    }  
  11. }  
The default modifier is more restrictive than protected. That is why there is compile time error.


Post a Comment

0 Comments