Java Programming Constructors

What is constructor?

  • Constructor is similar like a method, constructor name should be same as class name.
  • Constructor is used to perform the automatic initialization for class instance members.
  • Constructor initializes object upon object creation.
  • Once constructor is defined, constructor is automatically called immediately after the object is created but before the new operator completes.
  • Constructor does not have return type and not even void, implicit return type of a constructor is a class type itself.

What are the different types of constructors in java?

There are two types of constructors:
  • Default constructor (no argument constructor)
  • Parameterized constructors

Default constructor - No argument constructor

class Student {                                                                 
 String name;                                                                   
 int mark1, mark2, mark3;                                                       
                                                                                
 //Constructor                                                                  
 Student() {                                                                    
  System.out.println("Initializing student objects");                           
  name = "test1";                                                               
  mark1 = 75;                                                                   
  mark2 = 80;                                                                   
  mark3 = 65;                                                                   
 }                                                                              
                                                                                
 int getTotalMarks() {                                                          
  return (mark1 + mark2 + mark3);                                               
 }                                                                              
}                                                                               
class JavaConstructor {                                                         
 public static void main(String args[]) {                                       
  Student student1 = new Student();                                             
  Student student2 = new Student();                                             
                                                                                
  System.out.println("Student1: " + student1.getTotalMarks());                  
  System.out.println("Student2: " + student2.getTotalMarks());                  
 }                                                                              
}    
Output:
$ java JavaConstructor
Initializing student objects
Initializing student objects
Student1: 220
Student2: 220

Parameterized Constructors

class Student {                                                                 
 String name;                                                                   
 int mark1, mark2, mark3;                                                       
                                                                                
 //Constructor                                                                  
 Student(String n, int m1, int m2, int m3) {                                    
  System.out.println("Initializing student objects");                           
  name = n;                                                                     
  mark1 = m1;                                                                   
  mark2 = m2;                                                                   
  mark3 = m3;                                                                   
 }                                                                              
                                                                                
 int getTotalMarks() {                                                          
  return (mark1 + mark2 + mark3);                                               
 }                                                                              
}                                                                               
class JavaConstructor1 {                                                        
 public static void main(String args[]) {                                       
  Student student1 = new Student("test1", 75, 45, 89);                          
  Student student2 = new Student("test2", 87, 78, 98);                          
                                                                                
  System.out.println(student1.name + ": " + student1.getTotalMarks());          
  System.out.println(student2.name +": "  + student2.getTotalMarks());          
 }                                                                              
}   
Output:
$ java JavaConstructor1
Initializing student objects
Initializing student objects
test1: 209
test2: 263

What is the use of this keyword?

this keyword is used to refer the current instance or object. this is always a reference to the object on which method is invoked.
 //Constructor                                                                  
 Student(String name, int mark1, int mark2, int mark3) {                        
  System.out.println("Initializing student objects");                           
  this.name = name;                                                             
  this.mark1 = mark1;                                                           
  this.mark2 = mark2;                                                           
  this.mark3 = mark3;                                                           
 }                                                                              

What is instance variable hiding?

  • It is not legal in java declaring two local variables in same name in the same or enclosing scopes.
  • If instance variable and local variable have same name, then local variable hides the instance variable.
class Student {                                                                 
 String name;                                                                   
 int mark1, mark2, mark3;                                                       
                                                                                
 //Constructor                                                                  
 Student(String name, int mark1, int mark2, int mark3) {                        
  System.out.println("Initializing student objects");                           
  name = name;                                                                  
  mark1 = mark1;                                                                
  mark2 = mark2;                                                                
  mark3 = mark3;                                                                
 }                                                                              
                                                                                
 int getTotalMarks() {                                                          
  return (mark1 + mark2 + mark3);                                               
 }                                                                              
}                                                                               
                                                                                
class JavaConstructor2 {                                                        
 public static void main(String args[]) {                                       
  Student student1 = new Student("test1", 75, 45, 89);                          
  Student student2 = new Student("test2", 87, 78, 98);                          
                                                                                
  System.out.println(student1.name + ": " + student1.getTotalMarks());          
  System.out.println(student2.name +": "  + student2.getTotalMarks());          
 }                                                                              
}  
Output:
$ java JavaConstructor2
Initializing student objects
Initializing student objects
null: 0
null: 0

Accessing instance variable using this keyword

this keyword is used to access instance variable and differentiates with local variable in same scopes.
class Student {                                                                 
 String name;                                                                   
 int mark1, mark2, mark3;                                                       
                                                                                
 //Constructor                                                                  
 Student(String name, int mark1, int mark2, int mark3) {                        
  System.out.println("Initializing student objects");                           
  this.name = name;                                                             
  this.mark1 = mark1;                                                           
  this.mark2 = mark2;                                                           
  this.mark3 = mark3;                                                           
 }                                                                              
                                                                                
 int getTotalMarks() {                                                          
  return (this.mark1 + this.mark2 + this.mark3);                                
 }                                                                              
}                                                                               
                                                                                
class JavaConstructor2 {                                                        
 public static void main(String args[]) {                                       
  Student student1 = new Student("test1", 75, 45, 89);                          
  Student student2 = new Student("test2", 87, 78, 98);                          
                                                                                
  System.out.println(student1.name + ": " + student1.getTotalMarks());          
  System.out.println(student2.name +": "  + student2.getTotalMarks());          
 }                                                                              
}     
Output:
$ java JavaConstructor2
Initializing student objects
Initializing student objects
test1: 209
test2: 263

Overloading Constructors

Overloaded constructor is called based upon the parameters specified when new is created for object creation.
class Student {                                                                 
 String name;                                                                   
 int mark1, mark2, mark3;                                                       
                                                                                
 //Constructor                                                                  
 Student() {                                                                    
  System.out.println("Initializing student objects");                           
  name = "test1";                                                               
  mark1 = 75;                                                                   
  mark2 = 80;                                                                   
  mark3 = 65;                                                                   
 }                                                                              
                                                                                
 Student(String name, int mark1, int mark2, int mark3) {                        
  System.out.println("Initializing student objects");                           
  this.name = name;                                                             
  this.mark1 = mark1;                                                           
  this.mark2 = mark2;                                                           
  this.mark3 = mark3;                                                           
 }                                                                              
                                                                                
 int getTotalMarks() {                                                          
  return (this.mark1 + this.mark2 + this.mark3);                                
 }                                                                              
}                                                                               
                                                                                
class JavaConstructor2 {                                                        
 public static void main(String args[]) {                                       
  Student student1 = new Student();                                             
  Student student2 = new Student("test2", 87, 78, 98);                          
                                                                                
  System.out.println(student1.name + ": " + student1.getTotalMarks());          
  System.out.println(student2.name +": "  + student2.getTotalMarks());          
 }                                                                              
}     
Output:
$ java JavaConstructor2
Initializing student objects
Initializing student objects
test1: 220
test2: 263

Java Programming Examples

GCD and Rational Number Java Program

Java Queue Program using exception

Java Stack Program using exception

Addition of three integers java program

Biggest of three integers java program

Fibonacci numbers java program

Arithmetic Operations Menu java program

Second Smallest Element In Array Java Program

Transpose Of A Matrix Java Program

Java Program to Display triangle of stars (*)

Java Programming Prints Product Tables

Java Program to Display triangle of numbers

Java Programming Gets Current Date

Java Programming Finds Character Vowel or Consonent

Java Programming HCF and LCM Computation

Java Programming Sum of Command Line Integer Arguments

Java Programming Multiplication of Command Line Integer Arguments

Java Programming Multiplication of Command Line Floating Point Numeric Arguments

Java Programming String Contains or Not

Java Programming Gets Grade Description using Switch

Java Programming CSV File Reader

Java Programming Character Frequency Count in String using for each

Java Programming Finds Min from Integer Array by Passing Array to Method

Java Programming Linear Search

Java Programming Binary Search

Java Programming Ternary Search

Java Programming Generates Range of Numbers

Java Programming Generates Range of Characters

Java Programming Computes Square Root Value

Java Programming Checks Number is Positive or Negative

Java Programming Checks Number is Odd or Even

Java Programming Computes Plot Area

Java Programming Convert Number of Days into Years

Java Programming Checks a Year is Leap Year, Century Year or Not

Java Programming Checks a Character is Digit, Letter or neither digit nor letter

Java Programming Checks a Number is Palindrome or not

Java Programming Sum of Two Matrix

Java Programming Power Computation

Java Programming Checks Number is an Armstrong Number or not

Java Programming Temperature Unit Conversions

Java Programming Generates Random Numbers in Specified Range

Java Programming Computes Sum of Digits and Product of Digits

Java Programming Computes Reverse Number

Java Programming Computes Factorial Value

Java Programming Checks Prime Number or not

Java Programming Computes Harmonic Series

Java Programming Generates Floyd's Triangle

Java Programming Reverses String

Java Programming Checks Palindrome String or not

Java Programming Opens Notepad

Java Programming Searches String using RegEx Pattern

Java Programming Searches Word in String

Java Programming Gets System Environment Variables

Java Programming Gets IP Address of Server Name

Java Programming Arrays Sort and Reverse using sort method

Java Programming Bubble Sorting

Java Programming Selection Sorting

Java Programming Insertion Sorting

Java Programming Merge Sorting

Java Programming Quick Sorting

Java Programming Counting Sort

Java Programming Radix Sorting

Java Programming Sorting Array of Strings

Java Programming String Characters Sorting

Java Programming Sum of First N Numbers

Java Programming Product of First N Numbers

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter
^