Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Constructors in Java

    The term "Java constructors" refers to the process of constructing or building elements within our programs. In Java, a constructor is a special method utilized for initializing objects. When we instantiate a class object, the constructor is called that allow us to set initial values for the object's attributes.

    In Java, a constructor is a code block that is smimilar to method but constructor name is same as class name . It is automatically called when a class instance is created, and it is critical in allocating memory for the object.



Table Of Content

  • Constructors in Java
  • Types of Constructor
  • Constructor Overloading in Java
  • Java Copy Constructor
  • Difference between Constructor and Method


Essentially, a constructor serves as a unique type of method that initializes the object during its creation. Whenever the new() keyword is employed to create an object, at least one constructor is invoked.The Java compiler will automatically provide a default constructor if a class does not provide a specific constructor.

The term "constructor" originates from its function of constructing or building the object's value at the time of its creation. Declaring a constructor is not mandatory every time a class is created since the Java compiler will supply a default constructor when necessary.


Note: Constructor is called constructor because it construct the value at time of object creation.It is not necessary to declare constructor every time you create class.Java compiler will provide default constructor if your class does not have constructor.




Rules for creating Java constructor

  • The constructor(s) name in object-oriented programming must have the same name as the class name in which constructor is define
  • Java does not allow final, abstract, static, or synchronised constructors.
  • In order to regulate the constructor's access, access modifiers can be used in its declaration.

Types of constructor

  • There are two types of constructor in Java:
    • Default constructor(No argument)
    • Parameterized constructor

Default constructor

  • Default Constructor is a constructor which doesn't have any parameter.
  • The compiler creates a constructor for a class without any arguments if a constructor is not defined in the class. The compiler does not produce a default constructor for you if you define a constructor.
  • Depending on the type, the default constructor gives the object default values like 0, null, etc. For example, Consider a "Person" class with member variables like "name" (a string) and "age" (an integer). when a new "Person" object is created using the default constructor then it would typically initialize the "name" variable to null and the "age" variable to 0




How to declare program using default constructor
 // Java  program using default constructor  
public class Student   
{  
    int Id;
    public Student() {
        System.out.println("Your ID is "+Id);
    }
    public static void main(String[] args) {
        Student student =new Student(); // when object is created constructor automatically invoked 
    }
} 

Output:

0  


Parameterized constructor

  • Constructors with parameters are referred to as parameterized constructors. They enable you to provide specific values during object creation to initialise a class's fields. By employing a parameterized constructor, you can create your own default values based on the arguments passed for the class's fields.

How to define Parameterized constructors
 // Java  program using class and object   
class Student{  
	public static void main(String args[]){  
		int x = 10;  
		int y = 20;  		
		int z = addition(x, y);   //Here x and y are actual parameters  & add method is called
		System.out.println("The sum of x and y is = " + z);  
	}  
		
	public static int addition(int a, int b)   //a and b are formal parameters 
        // Here Method is static so that we can access without object
	{  
		int sum;  
		sum=a+b;  
		return sum; //returning the sum  
	}
}  
 



Output:

The sum of x and y is = 30  

In the above example, we have used add method it is not already define so we have define it first and access in main method, we have made add method static because we can access static method without object. you wil learn about static method below this page


Constructor Overloading in Java

Method overloading refers to when a class has multiple methods with the same name but different parameter lists.


Example of Constructor Overloading
 // Constructor Overloading  program  
class Addition{  
	Addition(int x,int y){
		System.out.println("Sum of two number is : "+(x+y));
	}  
	Addition(int p,int q,int r){
		System.out.println("Sum of three number is : "+(p+q+r));
	}  
} 
class code_check{  
	public static void main(String args[]){  
          Addition addition=new Addition(12,13);
          Addition addition2=new Addition(12,13,15);
	}  
}

Output:

Sum of two number is : 25 
Sum of three number is : 40 

Java Copy Constructor


In Java, there are various methods available for copying the values of one object into another.

  • There are two types of constructor in Java:
    • By constructor
    • By assigning the values of one object into another
    • By clone() method of Object class

Java Copy Constructor
 // Java  program using class and object   
class codeCheck{
    int roll;
    String name; 
    codeCheck(int roll, String name) 
    {
    	this.roll = roll;
    	this.name = name;
    }
    codeCheck(codeCheck object)  //constructor to initialize another object
    {
    	roll = object.roll;  // object is object of  codeCheck class
	    name =object.name;
    }
    void display(){
    	System.out.println(roll+" "+name);
    }
 
    public static void main(String args[]) {
    	codeCheck code1 = new codeCheck(8650,"Dr Alok Raja");		
    	codeCheck code2 = new codeCheck(code1);   
    	code1.display();
	code2.display();
   }
}

Output:

8650 Dr Alok Raja 
8650 Dr Alok Raja 

Comparison Chart

Difference between constructor and method in Java are mention below


S.N Constructor Method
1. In Object-oriented programming (OOPS) constructor is a special method that is used to initialize an object A method is used to reveal an object's behaviour.
2. A return type is not permitted in a constructor. A return type is required for every method.
3. When a object is created with the "new" keyword, the constructor is invoked implicitly. Method needs to be invoked explicitly.
4. The Java compiler will automatically provide a default constructor if a class doesn't define one The compiler in any situation does not supply the method.
5. The class name and constructor name are same. The class name and the method name might or might not be the same.


Java Static Keyword Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.