• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Classes » Constructor Methods in java
Next →
← Prev

Constructor Methods in java

By Dinesh Thakur

Constructor methods initialize new objects when they are created. Unlike regular methods, constructor methods cannot be called directly. They are called automatically when a new object is created. When an object is created in Java using the keyword new the following things happen:

• Memory is allocated for the new object.

• Instance variables of the object are initialized, either to their initial values or to default values (0 for numbers, null for objects, false for boolean, ‘\0’ for characters.)

• A constructor method is invoked. (A class may have one or more constructor methods with different arguments lists. Based on the number of parameters and their data types, the corresponding constructor will be invoked.)

If a class does not have any defined special constructor methods, the instance variables of the new object should be set or other methods that are needed by the object to initialize itself should be called.

By defining constructor methods in classes, the initial values of instance variables can be set. Java also facilitates overloading of constructors. Constructor overloading helps to create an object that has specific properties defined on the basis of the arguments given in the new expression.

Basic constructors

Constructors look a lot like regular methods, with two basic differences:

• Constructors always have the same name as the class.

• Constructors do not have a return type .

Program shows a simple class by the name Identity. The constructor method for Identity takes two arguments: a string object representing its name and an integer that stands for its age.

Using constructors.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Identity {
  String name;
  int age;
  Identity (String n, int a) {
   name = n;
   age = a;
  }
 void printldentity() {
   System.out.print("Name is" + name);
   System.out.printin("Age is" + age);
 }
 public static void main (String args[]) {
   Identity I;
   I = new Identity("Shyam", 30);
   I.printldentity ();
   System.out.println(" -------- ") ;
   I = new Identity("Johnny", 3);
   I.print Identity ();
   System.out.printIn(" -------- ") ;
 }
}

The output of this program is as follows:

Name is Shyam

Age is 30

Name is Johnny

Age is 3

The Identity class has three methods, The first is the constructor method which initializes the two instance variables of the class based on the arguments to new, The Identity class also includes a method called printIdentity() so that the object can ‘introduce’ itself and a main() method to test each of these things.

Calling another constructor

Some constructors may be supersets of other constructors defined within a class. This implies that the constructor might have the same behaviour as the other constructor plus other additional behaviour. Rather than duplicating identical behaviour in multiple constructors in a class, it is recommended to just call the first constructor from inside the body of the second constructor. Java provides a special syntax for doing this. A constructor defined within the current class can be called using the keyword this. The syntax would be as follows:


1
this(arg1, arg2, arg3,..);

The arguments to this() are the arguments to the constructor.

Overloading constructors

Similar to methods, constructors can take many different numbers and types of parameters in the body of one program, enabling the programmer to create objects with desired functionality.

Program shows the example of a class Rectangle that has overloaded constructors.

Using overloaded constructors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.awt.Point;
class Rectangle {
  int x1 = 0;
  int y1 = 0;
  int x2 = 0;
  int y2 = 0;
  Rectangle(int x1, int y1, int x2, int y2) {
    this.x1 = x1;
    this.y1 = y1;
    this.x2 = x2;
    this.y2 = y2;
 }
 Rectangle(Point top Left. Point bottomRight) {
   x1 = topLeft.x;
   y1 = topLeft.y;
   x2 = bottomRight.x;
   y2 = bottomRight.y;
 }
 Rectangle(Point top Left. int w. int h) {
    x1 = topLeft.x;
    y1 = topLeft.y;
    x2 = (x1 + w);
    y2 = (y1 + h);
 }
 void printRect() {
   System.out.print("Rectangle: <" + x1 + “ , “+ y1);
   System.out.println("," + x2 + "," + y2 + ">");
}
 public static void main(String args[]) {
   Rectangle rect;
   System.out.println("Calling Rectangle with coordinates 5,5,25,25:");
   rect = new Rectangle(5. 5, 25. 25);
   rect.printRect();
   System.out.println(“………”);
   System.out.println("Calling Rectangle with points (10,10). (20,20):");
   rect = new Rectangle(new Point(10,10), new Point(20.20));
   rect.printRect();
   System.out.println(" -----------");
   System.out.print("Calling Rectangle with point (10,10)");
   System.out.println(" width (50) and height (50):");
   rect = new Rectangle(new Point(1 0.1 0). 50, 50);
   rect.printRect();
   System.out.printIn(" ---------- ") ;
 }
}

The output of Program is the following:

Calling Rectangle with coordinates 5,5,25,25:

MyRect: <5, 5, 25, 25>

Calling Rectangle with points (10,10), (20,20):

MyRect:<1 0,10,20,20>

Calling Rectangle with point (10,10), width (50) and height (50):

MyRect: < 10, 10,60, 60>

You’ll also like:

  1. Define a Constructor. What it is and how it might be called (2 methods)
  2. Calling Constructor from Constructor Java
  3. Default Constructor in Java with Example
  4. Parameterized Constructor in Java Example
  5. Constructor Overloading in Java with Example
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW