header

For BE/B.Tech/BCA/MCA/ME/M.Tech Major/Minor Project for CS/IT branch at minimum price Text Message @ 9424820157

Constructors in Java

 Constructors in Java



Constructors are used to allocating memory to an object for instantiation. "new" keyword is used along with the constructor to allocate memory.

Here is a simple example to allocate memory to an object for instantiation.


package Hello; 

public class TestConstructor {

 public static void main(String[] args) {
  
TestConstructor tc = new TestConstructor();

 }
}

Here, TestConstructor() is constructor and "new" is keyword.

Important features regarding Constructors :

1) Constructor name must be the same as that of the class name.
2) Constructors do not have any return type.
3) Access modifiers can be used along with constructors.
4) it is used to initialize/instantiate instance variables/objects.
5) A class can have multiple constructors with different parameters.
6) if no constructor is defined in class then a default constructor is created by the compiler.
7) if we define multiple constructors in class then we must define a default constructor in that class.
8) Constructor is similar to the method in java
9) Constructor can be overload but not override.
10) Interface does not support the constructor.
11) We can declare both default and parameterized constructors in abstract class but cannot call in it for object instantiation. We can call constructors in the concrete class of that abstract class.

Types of constructors in Java
Basically, there are two types of constructors in java : 

1) default constructor
2) parameterized constructor.

Example program to show default and parameterized constructor : 


package Hello;
public class TestConstructor {

 int i=10;
 String name = null;

 public TestConstructor(){
 System.out.println("in default constructor");
 }

 public TestConstructor(int i,String name){
       System.out.println("in parameterized constructor");
  this.i = i;
  this.name = name;
 System.out.println(i+" "+name);
 }
 public static void main(String[] args) {
  
TestConstructor tc = new TestConstructor();
TestConstructor tc1 = new TestConstructor(1,"Himanshu");
 }
}

Output : 
in default constructor
in parameterized constructor
1 Himanshu

Default constructor :

A constructor with zero arguments is known as the default constructor. We should define the default constructor in our program but if we do not create it in our program then the compiler itself creates the default constructor.

Example showing instance created by using the default constructor and printing initialized values.

package Hello;

public class TestDefaultConstructor {

private int i=8;
private float f=8.0f;
private String str="8";

public TestDefaultConstructor(){
 }

public void a(){
 System.out.println("i : "+i);
 System.out.println("f : "+f);
 System.out.println("str : "+str);
}
public static void main(String[] args) {
 TestDefaultConstructor tdc = new TestDefaultConstructor();
 tdc.a();
}
}
Output : 
i : 8
f : 8.0
str : 8


Parameterized constructor : 
Constructors with arguments are known as parameterized constructors.

Example program showing parameterized constructor : 

package Hello;

public class TestParamConstructor {
 private int salary;
 private String employees;

 public TestParamConstructor(){
 
 }

public TestParamConstructor(int sal,String emp){
  salary = sal;
  employees = emp;
 }
 public static void main(String[] args) {
 TestParamConstructor tpc = new TestParamConstructor(90000,"Himanshu");
  System.out.println(tpc.salary);
  System.out.println(tpc.employees);
 
 }

}
Output : 

90000
Himanshu

Example showing constructor is not allowed in Interface :

package Hello;

public interface TestConstructorInt {

 public TestConstructorInt(){

 }
}

Output :
compile time error

     
A constructor cannot be called in abstract class but it can call in its concrete class. 

package Hello;

public abstract class TestConstructor {

 int i=10;
 String name = null;

 public TestConstructor(){
 System.out.println("in default constructor");
 }

 public TestConstructor(int i,String name){
System.out.println("in parameterized constructor");
  this.i = i;
  this.name = name;
  System.out.println(i+" "+name);
 }

public static void main(String[] args) {
 
/*TestConstructor tc = new TestConstructor();
TestConstructor tc1 = new TestConstructor(1,"Himanshu"); */

 }
}

if we uncomment the last two lines then it will give the compile-time error.

package Hello;

public class TestConstructor1 extends TestConstructor{

private int i=10;
 public static void main(String[] args) {
TestConstructor1 tc = new TestConstructor1();
System.out.println(tc.i);
 }
}
output :
in default constructor
10

Constructor chaining :
it is used to call a constructor in another constructor in the same class or in another class.

let's see an example of constructor chaining in the same class.

package Hello;

public class TestConsChaining {
 private int i=0;
 private int j=10;

 public TestConsChaining(){
 System.out.println("default constructor");
 }

public TestConsChaining(int i){
 this();
 this.i = i;
System.out.println("in one param constructor");
 }

public TestConsChaining(int i,int j){
 this(i);
 this.j = j;
System.out.println("in two param constructor");
 }

public static void main(String[] args) {
TestConsChaining tcc = new TestConsChaining(400,600);
  System.out.println(tcc.i);
  System.out.println(tcc.j);
 }
}


Output :
default constructor
in one param constructor
in two param constructor
400
600

Note: In the above example, this() is used to call the constructor of the same class.

Now see an example of constructor chaining in child class.

package Hello;

public class TestConstructor {

 int i=0;
 String name = null;

 public TestConstructor(){
  System.out.println("in default constructor");
 }

 public TestConstructor(int i,String name){
  System.out.println("in parameterized constructor");
  this.i = i;
  this.name = name;
  System.out.println(i+" "+name);
 }

 public static void main(String[] args) {
 
     TestConstructor tc = new TestConstructor();
 TestConstructor tc1 = new TestConstructor(1,"Himanshu");
  System.out.println(tc.i);
  System.out.println(tc.name);
 }

}

package Hello;

public class TestConstructor1 extends TestConstructor{

private int i=0;
private String name=null;
private String city=null;

public TestConstructor1(){

}

public TestConstructor1(int i,String name){
 super();
}

public TestConstructor1(int i,String name,String city){
 super(i,name);
 this.city = city;

}

public static void main(String[] args) {

TestConstructor1 tc = new TestConstructor1(200,"sakshi");
TestConstructor1 tc1 = new TestConstructor1(200,"sakshi","pune");

 }
}

Output:
in default constructor
in parameterized constructor
200 sakshi

Note: In the above example super() is used to call the constructor of the parent class.

No comments:

Post a Comment



Please go through below tutorials:


Mule 4 Tutorials

DEPLOY TO CLOUDHUB C4E CLIENT ID ENFORCEMENT CUSTOM POLICY RABBIT MQ INTEGRATION
XML TO JSON WEBSERVICE CONSUMER VM CONNECTOR VALIDATION UNTIL SUCCESSFUL
SUB FLOW SET & REMOVE VARIABLE TRANSACTION ID SCATTER GATHER ROUND ROBIN
CONSUME REST WEBSERVICE CRUD OPERATIONS PARSE TEMPLATE OBJECT TO JSON LOAD STATIC RESOURCE
JSON TO XML INVOKE IDEMPOTENT FILTER FOR EACH FLAT TO JSON
FIXWIDTH TO JSON FIRST SUCCESSFUL FILE OPERATIONS EXECUTE ERROR HANDLING
EMAIL FUNCTIONALITY DYNAMIC EVALUATE CUSTOM BUSINESS EVENT CSV TO JSON COPYBOOK TO JSON
CHOICE ASYNC

Widely used Connectors in Mule 3

CMIS JETTY VM CONNECTOR SALESFORCE POP3
JMS TCP/IP WEBSERVICE CONSUMER QUARTZ MONGO DB
FILE CONNECTOR DATABASE CONNECTOR


Widely used Scopes in Mule 3

SUB FLOW REQUEST REPLY PROCESSOR CHAIN FOR EACH CACHE
ASYNC TCP/IP COMPOSITE SOURCE POLL UNTIL SUCCESSFUL
TRANSACTIONAL FLOW

Widely used Components in Mule 3

EXPRESSION CXF SCRIPT RUBY PYTHON
JAVASCRIPT JAVA INVOKE CUSTOM BUSINESS EVENT GROOVY
ECHO LOGGER


Widely used Transformers in Mule 3

MONGO DB XSLT TRANSFORMER REFERENCE SCRIPT RUBY
PYTHON MESSAGE PROPERTIES JAVA TRANSFORMER GZIP COMPRESS/UNCOMPRESS GROOVY
EXPRESSION DOM TO XML STRING VALIDATION COMBINE COLLECTIONS BYTE ARRAY TO STRING
ATTACHMENT TRANSFORMER FILE TO STRING XML TO DOM APPEND STRING JAVASCRIPT
JSON TO JAVA COPYBOOK TO JSON MAP TO JSON JSON TO XML FLATFILE TO JSON
FIXWIDTH TO JSON CSV TO JSON


Widely used Filters in Mule 3

WILDCARD SCHEMA VALIDATION REGEX PAYLOAD OR
NOT MESSAGE PROPERTY MESSAGE IDEMPOTENT FILTER REFERNCE
EXPRESSION EXCEPTION CUSTOM AND


Exception Strategy in Mule 3

REFERENCE EXCEPTION STRATEGY CUSTOM EXCEPTION STRATEGY CHOICE EXCEPTION STRATEGY CATCH EXCEPTION STRATEGY GLOBAL EXCEPTION STRATEGY


Flow Control in Mule 3

CHOICE COLLECTION AGGREGATOR COLLECTION SPLITTER CUSTOM AGGREGATOR FIRST SUCCESSFUL
MESSAGE CHUNK AGGREGATOR MESSAGE CHUNK SPLITTER RESEQUENCER ROUND ROBIN SOAP ROUTER