Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java Constructor: Overview

In this article we will discuss a little information about the Java Programming Language and you will learn completely about the Constructor in the Java Programming Language.

Programming is becoming a complex one when the recent trends in the technology have been evolved. Since the people seeking improvement in everything, we need to improve our source of providing better stuffs to the people. Java Programming Language is a high level programming languages which is used for creating high level applications for the users present in this technology era.

Java Programming Language

Java is a computer language that is used for programming. And it is used to develop the desktop applications and games for PC. The applications developed from the Java programs are very much essential when they are planned to run on different platforms. The main advantage of the Java programming language is that Java language is very easy to learn and it is totally object oriented. If you learn the java language, you can easily code various programs using the java programming language. The java language is totally distributed while comparing to other languages that allows you to work in the distributed environment. You can easily share various objects in the java programming language. The Java programming language is concurrent, class based, object oriented and they are specifically designed to have as much low dependencies as possible. This java programming language supports WORA. WORA means “Write Once, Run Anywhere”.

What is Constructor in Java?

Basically, the constructor concepts are found in the object oriented programs. Since the Java programming language has the OOPs concept, the constructor is also found in it.

Definition: In Java programming language, the constructor is defined as the type of subroutine in the class which is used to create an object in/for the class. It creates objects in the program and also it initiates the object for the further use in the program. The constructor has the same name of the class in which it resides. The concept of constructor brought a huge change in the Java programming language.

Here I have given a sample program for the Constructor concept in the java programming language and you can have an idea of constructor here.

Listing 1: programming.java

Import java.io.*;
class Programming {
//constructor method
  Programming(){
System.out.println("Constructor method called.");
}
publicstaticvoid main(String[] args){
    Programming object =new Programming();//creating object
}
}

In this program, I have created a class called a Programming. And also in the next step you can see that another thing is given which is similar to the class name.

programming() is the constructor which is declared in the program. The name of the constructor is same as the class name. In the void main section of the class, an object is created in the name “object”. When an object is created, then the constructor is invoked. Thereby the statement is printed as the output. The output “Constructor method called” is printed in the output.

Types of Constructor:

In Java programming language, the constructor is classified into two types and which are given as follows;

  • Default constructor and
  • Parameterized constructor.
 Types of Constructor

Figure 1: Types of Constructor

In Java programming language, the constructor is used to construct a value for an object.

Default Constructor:

The default constructor is a type of constructor which doesn’t have any parameters in it. It is also called as No-Argument Constructor, and it is a nullary constructor.

The syntax for the Default constructor is given as follows;

<class_name>(){}

Where, the class_name denotes the name of the class in which the constructor resides.

Listing 2: Example Program for Default Constructor:

package com.myjava.constructors;
  public classMyDefaultConstructor {
        public MyDefaultConstructor(){
                System.out.println("I am inside default constructor...");
        }
        public static void main(String a[]){
                MyDefaultConstructor mdc = newMyDefaultConstructor();
        }
}

In the above program, the default constructor is used. You can notice that, there is no parameters are given in the constructor.

Note: If a class has no constructor it, then the compiler will automatically initiate the objects by creating a default constructor.

Listing 3: Student.java example which shows the value in the constructor.

class  Student{    
int  id;    
String  name;    
    
void  display(){System.out.println(id+"  "+name);}    
    
public  static  void  main(String  args[]){    
Student  s1=new  Student();    
Student  s2=new  Student();    
s1.display();    
s2.display();    
}    
}    
Output:

0 null
0 null

Here the program has no constructor. But while creating an object, the program automatically creates a default constructor to initiate the objects in the class.

Parameterized Constructor:

The parameterized constructor is a constructor which has a arguments in it. The parameterized constructor has a value and it takes a value when you give in a program. The argument can be integer value, character, or an array. We can also give object in the Parameterized constructor. In the following example, you can see the parameterized constructor here;

Listing 4: Cube1.java

public class Cube1 {

	int length;
	int breadth;
	int height;
	public int getVolume() {
		return (length * breadth * height);
	}
	Cube1() {
		length = 10;
		breadth = 10;
		height = 10;
	}
	Cube1(int l, int b, int h) {
		length = l;
		breadth = b;
		height = h;
	}
	public static void main(String[] args) {
		Cube1 cubeObj1, cubeObj2;
		cubeObj1 = new Cube1();
		cubeObj2 = new Cube1(10, 20, 30);
		System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
		System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
	}
}

The above program has a parameterized constructor which has an argument in it. By using the parameterized constructor we can easily give various inputs in the program. This will reduce the code and code complexity can be easily reduced by using it.

Use of parameterized constructor:

  • We can give various inputs in the constructor if we use parameterized constructor.
  • It reduces the code redundancy.
  • Complexity can be reduced with the help of parameterized constructor.

An Example program for the Parameterized constructor, which is similar to the Default constructor.

Listing 5: Student.java

class  Student{    
        int  id;    
        String  name;    
        Student(int  i,String  n){    
        id  =  i;    
        name  =  n;    
        }    
        void  display(){System.out.println(id+"  "+name);}    
        public  static  void  main(String  args[]){    
        Student  s1  =  new  Student(111,"Karan");    
        Student  s2  =  new  Student(222,"Aryan");    
        s1.display();    
        s2.display();    
      }    
}    

Output:

111 Karan
222 Aryan

What are the rules to create a constructor in a Program?

There are mainly two things that are to be considered before writing a java program with constructor:

  • The constructor should have the same name of the class in which it resides.
  • The constructor should have no explicit return types.

Differences between the Method and the Constructor

The constructor is used to initialize the object and the method is used to expose the various behaviors of the objects. The method may have the return type by the constructor should not have any sort of return types in it. The constructor found in a program is invoked implicitly. But the method is explicitly invoked in the program.

How to copy one value in the constructor to the other values (similar to Copy Constructor in C++)?

In Java programming language, we can copy the values of one object into another by using the following methods;

  • By using the Constructor
  • By using Clone() method of the Object Class
  • By Using the value of one object into the other object.

Listing 6: Student.java Program to Copy one Values of one object to another.

class  Student{    
        int  id;    
        String  name;    
        Student(int  i,String  n){    
        id  =  i;    
        name  =  n;    
        }    
            
        Student(Student  s){    
        id  =  s.id;    
        name  =s.name;    
        }    
        void  display(){System.out.println(id+"  "+name);}    
      
        public  static  void  main(String  args[]){    
        Student  s1  =  new  Student(111,"Karan");    
        Student  s2  =  new  Student(s1);    
        s1.display();    
        s2.display();    
      }    
}    

Output:

111 Karan
111 Karan

Use of “This” Keyword:

In Java Programming language, the This Keyword is used to refer the instance of the class which is being executed. Instance of global variable can be used inside a method by using the “this” keyword. The following program provides a better example for this keyword.

Listing 7: Platypus.java

public class Platypus {
       String name;
       Platypus(String input) {
               name = input;
       }
       Platypus() {
               this("John/Mary Doe");
       }
       public static void main(String args[]) {
               Platypus p1 = new Platypus("digger");
               Platypus p2 = new Platypus();
       }
}

In this program, the “this” keyword is used to create an instance of the main class and also it is used to get the input from the global variable and it is used to store in a instance of a local variable inside a constructor.

Conclusion:

Java Programming Language allows you to create a better application for the technology world. If you want to learn a programming language, then the Java Programming Language is the best option for you.



Have experience over java, c++ c#, web-development, android development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login