What is constructor in java with example

Java Constructors

A constructor in Java is similar to a method that is invoked when an object of the class is created.

Unlike Java methods, a constructor has the same name as that of the class and does not have any return type. For example,

Here, Test() is a constructor. It has the same name as that of the class and doesn’t have a return type.

Example 1: Java Constructor

class Main < private String name; // constructor Main() < System.out.println("Constructor Called:"); name = "Programiz"; >public static void main(String[] args) < // constructor is invoked while // creating an object of the Main class Main obj = new Main(); System.out.println("The name is " + obj.name); >>
Constructor Called: The name is Programiz

In the above example, we have created a constructor named Main() . Inside the constructor, we are initializing the value of the name variable.

Notice the statement of creating an object of the Main class.

Here, when the object is created, the Main() constructor is called. And, the value of the name variable is initialized.

Hence, the program prints the value of the name variables as Programiz .

Types of Constructor

In Java, constructors can be divided into 3 types:

1. Java No-Arg Constructors

Similar to methods, a Java constructor may or may not have any parameters (arguments).

If a constructor does not accept any parameters, it is known as a no-argument constructor. For example,

Example 2: Java private no-arg constructor

class Main < int i; // constructor with no parameter private Main() < i = 5; System.out.println("Constructor is called"); >public static void main(String[] args) < // calling the constructor without any parameter Main obj = new Main(); System.out.println("Value of i: " + obj.i); >>
Constructor is called Value of i: 5

In the above example, we have created a constructor Main() . Here, the constructor does not accept any parameters. Hence, it is known as a no-arg constructor.

Notice that we have declared the constructor as private.

Once a constructor is declared private , it cannot be accessed from outside the class. So, creating objects from outside the class is prohibited using the private constructor.

Here, we are creating the object inside the same class. Hence, the program is able to access the constructor. To learn more, visit Java Implement Private Constructor.

Читайте также:  Случайное положительное число java

However, if we want to create objects outside the class, then we need to declare the constructor as public .

Example 3: Java public no-arg constructors

class Company < String name; // public constructor public Company() < name = "Programiz"; >> class Main < public static void main(String[] args) < // object is created in another class Company obj = new Company(); System.out.println("Company name /java-programming/access-modifiers">Java Access Modifier


2. Java Parameterized Constructor

A Java constructor can also accept one or more parameters. Such constructors are known as parameterized constructors (constructor with parameters).

Example 4: Parameterized constructor

class Main < String languages; // constructor accepting single value Main(String lang) < languages = lang; System.out.println(languages + " Programming Language"); >public static void main(String[] args) < // call constructor by passing a single value Main obj1 = new Main("Java"); Main obj2 = new Main("Python"); Main obj3 = new Main("C"); >>
Java Programming Language Python Programming Language C Programming Language

In the above example, we have created a constructor named Main() . Here, the constructor takes a single parameter. Notice the expression,

Here, we are passing the single value to the constructor. Based on the argument passed, the language variable is initialized inside the constructor.

3. Java Default Constructor

If we do not create any constructor, the Java compiler automatically create a no-arg constructor during the execution of the program. This constructor is called default constructor.

Example 5: Default Constructor

Programming Language: Java Programming Language: Python

In the above example, we have two constructors: Main() and Main(String language) . Here, both the constructor initialize the value of the variable language with different values.

Based on the parameter passed during object creation, different constructors are called and different values are assigned.

It is also possible to call one constructor from another constructor. To learn more, visit Java Call One Constructor from Another.

Note: We have used this keyword to specify the variable of the class. To know more about this keyword, visit Java this keyword.

Table of Contents

Источник

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 

Источник

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.

Источник

Оцените статью