
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
What are constructors in Java?
A constructor in Java is syntactically similar to methods. The difference is that the name of the constructor is same as the class name and it has no return type.
You need not call a constructor it is invoked implicitly at the time of instantiation. The main purpose of a constructor is to initialize the instance variables of a class.
Syntax
Following is the syntax of a constructor −
class ClassName { ClassName() { } }
While defining the constructors you should keep the following points in mind.
- A constructor does not have return type.
- The name of the constructor is same as the name of the class.
- A constructor cannot be abstract, final, static and Synchronized.
- You can use the access specifiers public, protected & private with constructors
Example
public class Test { int num; String data; Test(){ num = 100; data = "sample"; } public static void main(String args[]){ Test obj = new Test(); System.out.println(obj.num); System.out.println(obj.data); } }
Output
100 sample
- Related Articles
- What are Default Constructors in Java?
- What are copy constructors in Java?
- What are parametrized constructors in Java?
- Are Multiple Constructors possible in Java?
- What are constructors in C# programs?
- Constructors in Java\n
- How many types of constructors are there in Java?
- Get all Constructors in Java
- Type of Java constructors
- Can interfaces have constructors in Java?
- Can constructors be inherited in Java?
- Constructors of StringBuffer class in Java.
- Constructors of StringBuilder class in Java.
- Constructors of StringTokenizer class in Java.
- Are the constructors in an object invoked when de-serialized in Java?

Advertisements