- 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
Should a constructor always have the same name as the class in java?
Yes, the constructor should always have the same name as the class.
Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class.
If the programmer doesn’t write a constructor the compiler writes a constructors on his behalf.
Example
public class Sample{ public Sample(){ System.out.println("This is a constructor"); } public static void main(String args[]){ Sample obj = new Sample(); } }
Output
This is a constructor
- Related Articles
- Why the java file name should be always the same as a public class name?
- Why the constructor name is same as the class name in Java?
- Can a method have the same name as the class?
- Can we define a method name same as class name in Java?
- Why an interface doesn't have a constructor whereas an abstract class have a constructor in Java?
- Using predefined class name as Class or Variable name in Java
- Can we define multiple methods in a class with the same name in Java?
- Can we have a constructor private in java?
- Does a constructor have a return type in Java?
- How many public classes of the same name it can have in Java?
- How can we call one constructor from another in the same class in C#?
- What is the difference between simple name, canonical name and class name in a Java class?
- Class with a constructor to initialize instance variables in Java
- Why do we need a copy constructor and when should we use a copy constructor in Java?
- Display the package name of a class in Java

Advertisements