Constructor in java properties

What is Constructor in Java with Example – Constructor Chaining and Overloading

Constructor in Java is a block of code which is executed at the time of Object creation. But other than getting called, Constructor is entirely different than methods and has some specific properties like name of the constructor must be same as name of Class. Constructor also can not have any return type, constructor’s are automatically chained by using this keyword and super. Since Constructor is used to create object, object initialization code is normally hosted in Constructor. Similar to the method you can also overload the constructor in Java.

In this Java tutorial, we will some important points about constructor in Java which is worth remembering for any Java programmer.

It’s also worth remembering that any static initializer block is executed before constructor because they are executed when class is loaded into memory while constructors are executed when you create an instance of any object e.g. using new() keyword.

Constructor in Java – things to remember

What is Constructor in Java with example

Here are some important properties of constructor in Java, these are very specific to constructor only and does not apply to any other function or method.

Читайте также:  Включить debug в php

1. How to declare Constructor in Java

The first and most important rule of declaring a constructor is that name of constructor in Java must be exactly the same as the class on which you declare constructor, if it doesn’t then the compiler will flag an error.

A class in Java can have as many constructors as it and that is called constructor overloading in Java but the signature of two constructors must not be the same. here is an example of having multiple constructors in Java and how they are called using new() operator:

public class ConstructorDemo <
public ConstructorDemo () <
System. out . println ( «Inside no argument constructor» ) ;
>

public ConstructorDemo ( String name ) <
System. out . println ( «Inside one argument constructor in Java with name: » + name ) ;
>

public static void main ( String args []) throws IOException

ConstructorDemo d = new ConstructorDemo () ; //calling no argument constructor in java
ConstructorDemo e = new ConstructorDemo ( «Testing» ) ; //calling one argument constructor in java

Output:
Inside no argument constructor
Inside one argument constructor in Java with name: Testing

In the above example, we have created two separate object by calling two different constructors of the class ConstructorDemo . If you notice carefully name of the constructor is same as the name of the class. Also signature of the two constructors is different from each other.

2. Constructor and Return Type

Another important rule of declaring a constructor is that constructor in Java doesn’t have a return type. As I said constructor is different than methods in Java and doesn’t return anything, Java Constructors are by default of type void.

Though you can have a return statement inside the constructor without returning any value but can return control back to the caller. See the difference between method and constructor in Java for more differences.

3. Default and No Argument Constructor

Here comes another interesting property of constructor which is tested in SCJP and various other Java Exams and Java Interviews. Every Class in Java has constructor, if no explicit constructor is specified by Programmer, Java Compiler inserts a no argument constructor inside class. This is also called default Constructor in Java.

if you provide any constructor in Java e.g. with one argument or two argument than compiler will not add default constructor or no arguments constructor, which makes your class unusable with framework or library which uses reflection and follow Java Bean naming convention. So always provide no argument constructor in Java.

Another drawback of not providing no argument constructor is chances of having restricted hierarchy. Suppose another sub class is created and you don’t add constructor over there than compiler tries to create a default constructor which calls super() at first line.

super() means call to no argument constructor of super class and since there is no such constructor in your class it will fail with compilation error. This is like making your class final in Java.

4. Constructor Chaining

One more important property of constructor in Java is constructor chaining. Calling one constructor from another constructor in Java is called Constructor chaining. you can use the keyword this for calling the constructor of the same class and keyword super for calling the constructor of the superclass.

Anyway, call to the constructor must be on the first line of any constructor or else you will get a compilation error. Read more about constructor chaining and constructor overloading here.

5. Constructor and Access Modifiers

You can use any access modifier with a Java constructor. they can be public, protected or private. The default or no-argument constructor has the same access modifier as the class. You can also prevent a class from extension by making their constructor private .

With private constructor instance of that class can only be created inside declaring class. Singleton pattern in Java is a popular example of a Class with a private constructor.

6. Can Constructor be abstract, static, or final in Java

Constructor in Java can not be abstract , static, final or synchronized. These modifiers are not allowed for constructors.

7. Order of Initialization

Since parent class is initialized before child class in Java, The constructor of parent class is executed before the constructor of the child class, that explains why super() is the first statement in default no argument constructor. To understand more about how the class is loaded into memory read How ClassLoader works in Java and When class is loaded and initialized in JVM.

8. Constructor and Exception

A constructor can throw Exception in Java in fact constructor can declare Exception in their throws clause but that makes the caller handle or re-throw Exception while creating any instance of Class.

9. Constructor vs Factory Pattern

Creating an object using new() keyword and constructor has there pros and cons. It’s not good in terms of Encapsulation because if you directly create any instance of class you code is tied up with the structure of Constructor and any change in the constructor will require changes in all places where its object gets created. The standard way is to use factory design pattern in Java which encapsulates object creation logic and provides better maintenance over time.

10. Destructor

Unlike C++ there is no destructor in Java. Though objects have a finalize method which supposes to run before objects get garbage collected but that is not guaranteed by Java language specification and it may run or may not.

That’s all on What is constructor in Java and important points about constructor in Java. As you see there is a lot of rules and specific information around constructor but its an important aspect of the Java programming language and you must have a good grasp of all constructor specifics in Java. We have also touched on concepts like constructor chaining and constructor overloading which is quite popular on various Java exams.

Источник

Properties of Constructors in Java

A constructors 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. In Java, a 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. There are certain properties of constructors in java.

Properties of Constructors

1. Constructor Should not have any return type

If we declare a return type for a constructor, JVM considers it a normal method. The basic aim of the constructor is to assign a value to the object. It implicitly returns the address of the object.

2. The access specifier of the constructor can be private, default, protected, public

If the access specifier of the constructor is private, then an object of the corresponding class can be created in the context of the same class but not in the context of another class. If the access specifier of the constructor is the default, then an object of the corresponding class can be created in the context of classes that are in the same package. Similarly, if the constructor is declared as protected, the object of the corresponding class can be created in the context of classes of the same package as well as inherited classes of other packages. And, if the constructor is declared as public, the object of the corresponding class can be created in the context of any class.

3. A constructor cannot be declared as final and synchronized

The main purpose of using the final keyword is to restrict the overriding of a method (basically overriding is done in the context of inherited classes). As there is no concept of overriding constructors, declaring the final is useless. Using synchronized for a constructor raises a syntax error. Because only the thread that creates an object should have access to it while it is being constructed.

Источник

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