- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are the rules to create a constructor in java?
A constructor is used to initialize an object when it is created. It is syntactically similar to a method. The difference is that the constructors have same name as their class and, have no return type.
There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation.
Rules to be remembered
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
The following Java program demonstrates the creation of constructors.
public class Student { public String name; public int age; public Student(){ this.name = "Raju"; this.age = 20; } public void display(){ System.out.println("Name of the Student: "+this.name ); System.out.println("Age of the Student: "+this.age ); } public static void main(String args[]) { new Student().display(); } }
Output
Name of the Student: Raju Age of the Student: 20
- Related Articles
- What are the rules for calling the superclass constructor C++?
- How to create a parameterized constructor in Java?
- How to create a default constructor in Java?
- What are the constructor references in Java?
- What are the rules for a functional interface in Java?
- What are the differences between default constructor and parameterized constructor in Java?
- What are the rules on method overriding in Java?
- What are the rules to be followed while using varargs in java?
- How to create a constructor reference for an array in Java?
- What are the rules for a local variable in lambda expression in Java?
- What are the rules for formal parameters in a lambda expression in Java?
- What are the rules for the Subscriber interface in Java 9?
- What are the rules for the Subscription interface in Java 9?
- What are the rules for the Publisher interface in Java 9?
- What are the differences between a static block and a constructor in Java?

Advertisements