- Java Constructors
- What are Constructors in Java?
- Example
- Java
- How Java Constructors are Different From Java Methods?
- Need of Constructors in Java
- When Constructor is called?
- Types of Constructors in Java
- 1. Default Constructor in Java
- Providing Constructors for Your Classes
- Java Constructors
- Example
- Constructor Parameters
- Example
- Example
- What does java constructor do
- Java Default Constructor
- Syntax of default constructor:
- Example of default constructor
- Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
- Q) What is the purpose of a default constructor?
- Example of default constructor that displays the default values
- Java Parameterized Constructor
- Why use the parameterized constructor?
- Example of parameterized constructor
- Constructor Overloading in Java
- Example of Constructor Overloading
- Difference between constructor and method in Java
- Java Copy Constructor
- Copying values without constructor
- Q) Does constructor return any value?
- Can constructor perform other tasks instead of initialization?
- Is there Constructor class in Java?
- What is the purpose of Constructor class?
- Feedback
- Help Others, Please Share
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Java Constructors
Java constructors or constructors in Java is a terminology used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.
What are Constructors in Java?
In Java, Constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method that is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.
Example
Java
Note: It is not necessary to write a constructor for a class. It is because the java compiler creates a default constructor (constructor with no arguments) if your class doesn’t have any.
How Java Constructors are Different From Java Methods?
- Constructors must have the same name as the class within which it is defined it is not necessary for the method in Java.
- Constructors do not return any type while method(s) have the return type or void if does not return any value.
- Constructors are called only once at the time of Object creation while method(s) can be called any number of times.
Now let us come up with the syntax for the constructor being invoked at the time of object or instance creation.
class Geek < . // A Constructor Geek() < >. > // We can create an object of the above class // using the below statement. This statement // calls above constructor. Geek obj = new Geek();
The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-class or an overloaded constructor), if you don’t type in the call to super in your constructor the compiler will provide you with a non-argument call to super at the first line of your code, the super constructor must be called to create an object:
If you think your class is not a subclass it actually is, every class in Java is the subclass of a class object even if you don’t say extends object in your class definition.
Need of Constructors in Java
Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in the computer’s memory), then can a box be there with no value defined for its dimensions? The answer is No.
So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).
When Constructor is called?
Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class. Rules for writing constructors are as follows:
- The constructor(s) of a class must have the same name as the class name in which it resides.
- A constructor in Java can not be abstract, final, static, or Synchronized.
- Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.
So by far, we have learned constructors are used to initialize the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation.
Types of Constructors in Java
Now is the correct time to discuss the types of the constructor, so primarily there are three types of constructors in Java are mentioned below:
1. Default Constructor in Java
A constructor that has no parameters is known as default the constructor. A default constructor is invisible. And if we write a constructor with no arguments, the compiler does not create a default constructor. It is taken out. It is being overloaded and called a parameterized constructor. The default constructor changed into the parameterized constructor. But Parameterized constructor can’t change the default constructor.
Providing Constructors for Your Classes
A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarationsexcept that they use the name of the class and have no return type. For example, Bicycle has one constructor:
public Bicycle(int startCadence, int startSpeed, int startGear)
To create a new Bicycle object called myBike , a constructor is called by the new operator:
Bicycle myBike = new Bicycle(30, 0, 8);
new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.
Although Bicycle only has one constructor, it could have others, including a no-argument constructor:
Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike .
Both constructors could have been declared in Bicycle because they have different argument lists. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. You cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart. Doing so causes a compile-time error.
You don’t have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn’t have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object , which does have a no-argument constructor.
You can use a superclass constructor yourself. The MountainBike class at the beginning of this lesson did just that. This will be discussed later, in the lesson on interfaces and inheritance.
You can use access modifiers in a constructor’s declaration to control which other classes can call the constructor.
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:
Example
// Create a Main class public class Main < int x; // Create a class attribute // Create a class constructor for the Main class public Main() < x = 5; // Set the initial value for the class attribute x >public static void main(String[] args) < Main myObj = new Main(); // Create an object of class Main (This will call the constructor) System.out.println(myObj.x); // Print the value of x > > // Outputs 5
Note that the constructor name must match the class name, and it cannot have a return type (like void ).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:
Example
public class Main < int x; public Main(int y) < x = y; >public static void main(String[] args) < Main myObj = new Main(5); System.out.println(myObj.x); >> // Outputs 5
You can have as many parameters as you want:
Example
public class Main < int modelYear; String modelName; public Main(int year, String name) < modelYear = year; modelName = name; >public static void main(String[] args) < Main myCar = new Main(1969, "Mustang"); System.out.println(myCar.modelYear + " " + myCar.modelName); >> // Outputs 1969 Mustang
What does java constructor do
Java Default Constructor
A constructor is called «Default Constructor» when it doesn’t have any parameter.
Syntax of default constructor:
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. |
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
Q) What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type.
Example of default constructor that displays the default values
Explanation:In the above class,you are not creating any constructor so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types.
Example of Constructor Overloading
Difference between constructor and method in Java
There are many differences between constructors and methods. They are given below.
Java Constructor | Java Method |
---|---|
A constructor is used to initialize the state of an object. | A method is used to expose the behavior of an object. |
A constructor must not have a return type. | A method must have a return type. |
The constructor is invoked implicitly. | The method is invoked explicitly. |
The Java compiler provides a default constructor if you don’t have any constructor in a class. | The method is not provided by the compiler in any case. |
The constructor name must be same as the class name. | The method name may or may not be same as the class name. |
Java Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
- By constructor
- By assigning the values of one object into another
- By clone() method of Object class
In this example, we are going to copy the values of one object into another using Java constructor.
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.
Q) Does constructor return any value?
Yes, it is the current class instance (You cannot use return type yet it returns a value).
Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting a thread, calling a method, etc. You can perform any operation in the constructor as you perform in the method.
Is there Constructor class in Java?
What is the purpose of Constructor class?
Java provides a Constructor class which can be used to get the internal information of a constructor in the class. It is found in the java.lang.reflect package.
For Videos Join Our Youtube Channel: Join Now
Feedback
Help Others, Please Share
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter