digitization, transformation, binary

Constructor in Java:

After creating an object, we need to initialize it. Now initialization may happen through an instance method. But that needs to be called explicitly. Using constructor is the second option where the initialization happens automatically.

Objects are created with a new operator and with some method call. This method call is nothing but the constructor. Which is responsible for creating the object properly and all objects we create, must be given some initial values to the variables, they contain.

We can do this by using a dot(.) operator to access the instance variables and then assign some values individually. But we look at this approach, it is the very tedious and manual intensive approach to work with the variables individually.

Secondly, we need to call a method of that class to provide values of the instance variables.

like-

obj.setData(10,15);

Java provides a simpler, cleaner and more concise way to initialize the instance variable while creating an object. The way is called the use of the constructor.

What is Constructor?

A constructor is a special method in java that is used to create or construct an instance of a class and initialize the member variables of the newly constructed object. Object construction enables java run time environment to respond to a call(to an object’s constructor to create an actual object and store it in memory).

It is called just after the memory allocation for the object. It can be used to initialize the variables of the object to desired values or starting values at the time of object creation. It can be said that an object or instance of a class does not exist in memory until it’s constructor is called.

So the constructor performs necessary initialization for a new object. The new keyword creates a new dynamic instance of the class i.e it allocates the new object. The constructor method then called, passing the new object implicitly(this keyword reference) and passing the arguments specified between parameters explicitly.

It is not mandatory to provide a constructor for a class. If no user-defined constructor is provided, the compiler, during compile time, puts one, called as default constructor and initializes the variable with its default value.

For numeric data types variables are set to zero(0), for character datatypes the variables are set to ” or null, for reference variables are set to null.

The Constructor class represents a constructor of a class. A Constructor object can be obtained by calling the getConstructor() method of a Class object. Constructor provides methods for getting the name, modifiers, parameters, exceptions, and declaring class of a constructor. The newInstance() method can create a new instance of the class that declares a constructor.

Types of constructors:-

The constructor can be –

  • Default Constructor
  • Zero argumented Constructor
  • Argumented Constructor

Default Constructor:-

If we do not explicitly define a constructor, Java provides one default Constructor. Every class by default has a default Constructor. Default Constructor does not take any argument and it does not have any statements in its body.

Zero Argumented Constructor:-

This is similar to the default constructor, but we explicitly define it in the class.

Parameterized Constructor:

This type of constructor accepts parameters. It is possible to overboard constructor just like methods.

The class structure of Constructor is given as

public final class java.lang.reflect.Constructor extends java.lang.Object
implements java.lang.reflect.Member {
// Instance Methods
public boolean equals(Object obj);
public Class getDeclaringClass();
public Class[] getExceptionTypes();
public native int getModifiers();
public String getName();
public Class[] getParameterTypes();
public int hashCode();
public native Object newInstance(Object[] initargs);
public String toString();
}

The details of the class structure are given as follows:

public boolean equals(Object obj);

public boolean equals(Object obj) method returns true if obj is an instance of Constructor, and it is equivalent to this Constructor.

This method returns true if the objects are equal; false if they are not.

Parameter
obj – The object to be compared with this object.

public Class getDeclaringClass();

public Class getDeclaringClass() method returns the Class object for the class in which this constructor is declared.

This method returns the Class object that represents the class that declared this constructor.

public Class[] getExceptionTypes();

public Class[] getExceptionTypes() method returns an array of Class objects that represents the throws clause of this constructor. If the constructor does not throw any exceptions, an array of length 0 is returned.

This method returns an array that contains the Class objects that describe the exceptions that can be thrown by this constructor.

public native int getModifiers();

public native int getModifiers() method returns an integer value that represents the modifiers of this constructor. The Modifier class should decode the returned value.

This method returns an integer that represents the modifier keywords used to declare this constructor.

public String getName();

public String getName() method returns the name of this constructor, which is always the same as the name of the declaring class.

READ  Abstract Class FilterWriter in Java

This method returns the name of this constructor as a String.

public Class[] getParameterTypes();

public Class[] getParameterTypes() method returns an array of Class objects that represents the parameter types this constructor accepts. The parameter types are listed in the order in which they are declared. If the constructor does not take any parameters, an array of length 0 is returned.

This method returns an array that contains the Class objects that describe the parameter types that this constructor accepts.

public int hashCode();

public int hashCode() method returns a hashcode for this Constructor.

This method returns a hashcode for this object.

public native Object newInstance(Object[] initargs);

public native Object newInstance(Object[] initargs) method executes the constructor represented by this object using the given array of arguments. Thus, it creates and initializes a new instance of the declaring class of the constructor.

If a particular parameter is of a primitive type, the corresponding argument is automatically unwrapped and converted to the appropriate type, if possible. If that is not possible, an IllegalArgumentException is thrown.

If the constructor itself throws an exception, the exception is placed in an InvocationTargetException, which is then thrown to the caller of newInstance(). If the constructor completes normally, the newly created instance is returned.

This method returns the newly created object.

Parameter
initargs – An array of arguments to be passed to this constructor.

public String toString();

public String toString() method returns a string representation of this Constructor. This string contains the access modifiers of the constructor, if any, followed by the fully qualified name of the declaring class and a list of the parameters of the constructor if any.

The list is enclosed by parentheses, and the individual parameters are separated by commas.

If the constructor does not have any parameters, just the parentheses are included in the string.

This method returns a string representation of this object.

Apart from these Constructor class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

Constructors Vs other methods:

Constructors are not instance methods as they don’t belong to objects. They are only responsible for creating objects. They do exist before any object is created. In this way, they are static member function but according to the java language specification, they are not technically a member of the class hence they can not be static. They are not referred to as methods.

How Construct works:

The mechanism to call a constructor with a new keyword followed by the class name as constructor name with parameter list. The parameter list can be empty.


new (class name)(parameter list);
MyClass mc=new MyClass();
//or
new MyClass()
 

The constructor returns the reference of the newly created object. Sometimes we can call the constructor without creating a reference variable. It is legal but we can not use that object later as we did not store the object reference in the handle. They are ready to be garbage collected as soon as the execution is over.

The constructor does the following things:

  1. The constructor gets a block of unused memory in the heap. The memory is large enough to hold the specified object of the specified type.
  2. It initializes the instance variables of the object. If the declaration of an instance variable specifies an initial value, then the value is computed and stored in the instance variable. Otherwise, the default values are used.
  3. The actual parameters in the constructor, if any are evaluated and the values are assigned to the formal parameters of a constructor.
  4. The statements or the block part of the body of the constructor if any are executed.
  5. A reference to the object is returned as the value of the constructor call.

In the end, what we get is a reference to a newly created object. We can use this reference to get at the instance variables in that object or to call its instance methods.

Rules for creating constructor:

  1. The constructor name is same as class name
  2. It should not return any value(not even void).
  3. If we are providing an argumented constructor, the compiler assumes that we know how to use a constructor. Hence it does not put default constructor. We need to provide it.
  4. They can not be declared as static.
  5. The only modifier that can be used on a constructor definition is the access modifier-public, private and protected.

Example:


class MyDemo()
{
//if we do not mention any constructor the compiler will provide one default constructor
MyDemo()
{
}
}
 

working example:


class MyDemo()
{
int value1;
int value2;
MyDemo()
{
value1=10;
value2=20;
}
public void display(){
System.out.println("Value of Value1"+value1);
System.out.println("Value of Value2"+value2);
}
public static void main(String args[])
{
MyDemo md=new MyDemo();
md.display();
}
}
 

The objective of Constructors:

  1. create instances of a class and store it in memory.
  2. set default values to the variables.
  3. As the constructor does not have a return type, not even void, when the invocation is done, it simply returns the reference of the newly created in memory.
  4. The object reference is stored in memory. This gives us a way to ‘address’ or find our object in memory. Without this reference to this object, we can not call methods in the objects.

Default Constructors:

A default constructor is one which does not have argument. It is used to create a “vanilla object”.If we create a class with no constructor defined, the compiler will automatically create a one default constructor. It has the below roles:

  1. allocate memory for the new object.
  2. initialize the variables to default values.
class HelloWorld{
//no constructor is defined
     public static void print(){
        System.out.println("Hello World");
     }
}
public class DafaultConstructorTest{
    public static void main(String args[])
    {
        HelloWorld hw=new HelloWorld();
//default constructor is called even though we have not created it.
        hw.print();
    }
}
 

Initialization via Constructor

public class Circle{
private double x,y,r;
public Circle(){// With the default constructor we need to assign default values of
//x,y,r from outside of the class.
x=0.0;
y=0.0;
r=0.0;
public Circle(double x,double y,double r)
{
this.x=x;
this.y=y;
this.z=z;
}
public double circumference()
{
return 2*Math.PI*r;
}
public double area(){
return Math.PI*r*r;
}

We can make the variables public and can assign them in the following way:

Circle c=new Circle();
c.x=2.44;
c.y=1.62
c.z=.65

This is against the class design principle or the best practice. (Member elements of a class should be private and methods including constructors should be public.)

READ  Finally Keyword in Java Simplified

So the best way to initialize is as follows:

Circle c=new Circle(2.44,1.62,.65)

This will not break the principle and keep the variables private.

Constructor Overloading:

As constructors are methods hence the overloading concept also applies here. Constructors can be overloaded with different parameter lists.  A class can have any number of constructors that differ in the parameter lists.

The compiler differentiates these constructors by taking into account the number of parameters in the list and their type. So each of the constructors has some specific objective. In case the constructor is overridden and we want to use the default constructor, in that case, we need to define the default constructor.

In this case, we will be able to initialize an object in several different ways depending on the need.


public class MyDemo
{
MyDemo(int i)
{
}
MyDemo(float f)
{
}
}
 

In this case, if we try to create a vanilla object using a new MyDemo(), the compiler will throw an error stating that it can not find the constructor.
Say in the above example we need to create an instance with one variable initialized again we need to create an instance with two variable initialized, then we will write as below:


public class MyDemo
{
int value1;
int value2;
MyDemo()
{
//default constructor
}
//below are the augmented constructors
MyDemo(int a)
{
value1=a;
}
MyDemo(int a,int b)
{
value1=a;
value2=b;
}
public void display(){
System.out.println("Value of Value1->"+value1);
System.out.println("Value of Value2->"+value2);
}
public static void main(String args[])
{
MyDemo md1=new MyDemo();
md1.display();
MyDemo md2=new MyDemo(5);
md2.display();
MyDemo md3=new MyDemo(5,3);
md3.display();
}
}

The output of the code:
$javac MyDemo.java
$java -Xmx128M -Xms16M MyDemo
Value of Value1->0
Value of Value2->0
Value of Value1->5
Value of Value2->0
Value of Value1->5
Value of Value2->3
For the first 2 cases, we have called the default constructor and no value has been provided. In that case, the compiler has put the default values for the numeric datatypes that are 0,0
for the next 2 cases, value1 is initiated and value2 is still not initialized hence compiler has put 0.
for the last 2 cases both the values are initialized hence, we get what we passed in the argument list.

Constructor Chaining:(Calling constructor from Constructor):

This is useful when some other class extends to the base class using the extend keyword. To reduce the extra code, we can use the super keyword to call the base class’s constructor.
Let us take the earlier example:


public class MyDemo
{
int value1;
int value2;
MyDemo()
{
value1=1;
value2=1;
//some default values instead of zero(0).
}
//below are the argumented constructors
MyDemo(int a)
{
value1=a;
}
MyDemo(int a,int b)
{
value1=a;
value2=b;
}
public void display(){
System.out.println("Value of Value1->"+value1);
System.out.println("Value of Value2->"+value2);
}
public static void main(String args[])
{
DemoChild dc=new DemoChild();
dc.display();
}
}
class DemoChild extends MyDemo{
int value3;
int value4;
//extra variables
DemoChild()
{
super(5);
value3=3;
value4=4;
}
public void display(){
System.out.println("Value of Value1->"+value1);
System.out.println("Value of Value2->"+value2);
System.out.println("Value of Value3->"+value3);
System.out.println("Value of Value4->"+value4);
}
}

The output of the code:
$javac MyDemo.java
$java -Xmx128M -Xms16M MyDemo
Value of Value1->5
Value of Value2->0
Value of Value3->3
Value of Value4->4

Constructor Chaining:(using this keyword):

There could be another situation. When we write several constructors for a class, there are times when we would like to call one constructor from another. To avoid duplicating the code, we can do this calling by using this keyword.
this refers to the current object. In a constructor, this keyword takes on a different meaning when we pass in an argument list. It makes an explicit call to the constructor that matches the argument list. This makes it straight forward way to call the constructor.


public class Student{
    private String name=new String("null");
    private int roll=0;
    Student(int x)
    {
    roll=x;
    System.out.println("Constructor with int argument "+roll);
    }
    Student(String ss)
    {
        name=ss;
        System.out.println("Constructor with String argument "+name);
    }
    Student(int i,String s){
    //roll=i;
    //we can do this but another approach is
    this(i);
    //but we can not use this for another one
    name=s;
    //but we can do the below
    //this.name=s;
    System.out.println("Constructor with int and String argument "+roll+" "+name);
    }
Student()
{
this(10,"Sunil");
//default constructor
}
void print()
{
//this(11);
//not included in constructor hence we can not do this
// Student.java:32: error: call to this must be first statement in constructor
//this(11);
// ^
//1 error
System.out.println("Constructor with int and String argument "+roll+" "+name);
}
public static void main(String args[])
{
Student st=new Student();
st.print();
}
}

The output of the code:
$javac Student.java
$java -Xmx128M -Xms16M Student
Constructor with int argument 10
Constructor with int and String argument 10 Sunil
Constructor with int and String argument 10 Sunil
we can see another chaining in place.

The return type of Constructor

The return type is implicitly an instance of the class. No return type is specified in constructor deceleration nor is the void keyword is used. This object is implicitly returned. The constructor should not have used a return statement to return a value.

READ  Class ObjectStreamClass in Java

3 observations of Constructor:

  1. The Student(int I, String s) shows that while we can call one constructor using this keyword, we can not call two!!. The constructor call should be the first thing to do inside another constructor, otherwise, we will get an error.
  2. In case instance variable and parameter variable same then we need to use this.insatance_ variable=parameter variable, so that compiler doesn’t get confused.
  3. In the print method, this(11) gives an error during compilation. It means the compiler will not allow us to call a constructor from inside any other method which is not a constructor.

Rules for Constructor Chaining:

The body of the derived class constructor is called when we inherit, we know all about the base class and can access any public and protected members of the base class. This implies we must be able to assume that all members of the base class are valid when we are in the derived class. The way to generate the same is to call constructor first. The constructor will initialize all the respective members making “knowing all members are valid”.Next, we need to initialize all member objects(Objects placed in the class using composition)at their point of definition in the class. This ensures all base class members and member objects of the current object have been initialized.

  1. If super is not called then it will call the default constructor of the parent class. That means the base class constructor is called first. This step is repeated recursively until the root of the hierarchy is constructed first, followed by the next derived class, until the most derived class is reached.
  2. If super is used, it should be the first line of the constructor of the child constructor in child class.
  3. If super is called with a parameter, then an overridden constructor will be called to initialize the values. All other values will be set as zero(0).
  4. A constructor of a base class is always called the inside the constructor of the derived class. This goes in a chained manner until the last base class constructor is called.
  5. A derived class has access only to its members but not those of base class(whose members are mostly private). Only the corresponding base class constructors have the proper knowledge and access to initialize its elements. Thus all constructors must get called to ensure the object creation is proper and perfect.
  6. Member initializers are called in order of deceleration.

The compiler enforces a constructor call for every portion of a derived class. It will silently call the default constructor if we don’t explicitly call a base class constructor in the derived class constructor body. Also if we do not have one default constructor the compiler will place one and continue the constructor chain. Otherwise, if we do not have a default constructor but has an augmented constructor, the compiler will throw an Error.

The above-written concept is derived from the Constructor class defined in java.lang.reflect.Constructor class.

Class Constructor in Java

This class represents a constructor method of a class. Instances of constructors are obtained by calling getConstructor() and related methods of java.lang.Class. Constructor implements the Member interface, so we can use the methods of that interface to obtain the constructor name, modifiers, and declaring class. In addition, getParameterTypes() and getExceptionTypes() also return important information about the represented constructor.

In addition to these methods that return information about the constructor, the newInstance() method allows the constructor to be invoked with an array of arguments to create a new instance of the class that declares the constructor. If any of the arguments to the constructor are of primitive types, they must be converted to their corresponding wrapper object types to be passed to newInstance().

If the constructor causes an exception, the Throwable object it throws is wrapped within the InvocationTargetException that is thrown by newInstance(). Note that newInstance() is much more useful than the newInstance() method of java.lang.Class because it can pass arguments to the constructor.

The class structure for the class Constructor is given as

public final class java.lang.reflect.Constructor extends java.io.Object implements java.lang.reflect.Member {
// No Constructor
// Public Instance Methods
public boolean equals(Object obj); // Overrides Object
public Class getDeclaringClass(); // From Member
public Class[] getExceptionTypes();
public native int getModifiers(); // From Member
public String getName(); // From Member
public Class[] getParameterTypes();
public int hashCode(); // Overrides Object
public native Object newInstance(Object[] initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException,InvocationTargetException;
public String toString(); // Overrides Object
}

Constructor and Super keyword

Super Keyword:-
If a subclass wants to refer to its immediate superclass, it can use ‘super keyword’. Super has two specific usages.

  • Calling parent class’s constructor- When a child class wants to call parent class’s constructor then the syntax is
    super( ) or super(parameters) super( ) should be the first statement of the subclass’s constructor.
  • Access the super class’s member(If hiding using member hiding feature):-
    Using this we can force java to unhide the superclass member.
    Super.member;

Order of constructor calls:-

When a class hierarchy is formed the constructors are called in the order of derivation from parent ( super)class to subclass ( child class).

The super( ) is the first statement in child class’s constructor. If a proper super( ) is not written, the default constructor parameterless constructor of each superclass will be executed.

 

Ref: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

LEAVE A REPLY

Please enter your comment!
Please enter your name here