OCAJP – How to create and overload constructors in Java?

We are writing the series of posts on OCAJP certification exam. We are offering OCAJP 7, OCAJP 8, OCPJP 6, OCPJP 7 and OCPJP 8 for programmer level certifications. Keep watching our blog updates for the interesting tips on certification topics.

We have also written about how to prepare for OCAJP and how to prepare for OCPJP certifications. This posts are very useful if you are looking for guidance on preparing for the certification exams.

How to use constructors in Java - OCAJP Certification Exam

This post is about the OCAJP exam objective”Create and overload constructors; including impact on default constructors“.You will be tested in the exam about default constructors and constructor with return type. At the end of this article, you will be able to understand the different syntax’s for overloading the constructors.

What is Constructors in Java?

Constructors are block of code that are similar to a method that’s called when an instance of an object is created. The key differences between a constructor and a method is a constructor doesn’t have a return type and the name of the constructor must be the same as the name of the class. Where as a method has a retrun type.

Here is some of the characteristics of a constructor:

  • Constructor is like a method that contains exactly class name and has no return type.
  • Constructor will be called at the time of object creation.
  • When you are creating object, the corresponding constructor will be called.
  • If you type return type for constructor, it becomes a normal method but not a constructor.

Example :

public class Test {
	Test(){
		System.out.println("oca");//prints oca
	}
	public static void main(String[] args) {
		Test t =	new Test();	
	}

}
  • When you are creating Test class object, the corresponding constructor will be called. So it prints oca
  • In the above example, class name is Test so constructor name is also Test.
  • Constructor name must exactly match the class name.
  • If constructor name differs from class name , compiler gives compile time error.Because compiler thinks that you are supposed to write method but return type is missed.So it gives compile time error.
  • Look at the below example to understand this point

Example :

public class Test {
	test(){ //compile time error at this line
		System.out.println("oca");
	}
	public static void main(String[] args) {
		Test t =	new Test();	
	}

}

  • If you type return type for constructor, it becomes a normal method but not a constructor.
  • Look at the below example to understand this point

Example :

public class Test {
	void Test(){
		System.out.println("oca");
	}
	public static void main(String[] args) {
		Test t =	new Test();	
	}

}

  • If you run above program, you don’t get any output.Because there is return type for constructor, so it is a normal method.
  • To execute that method , you need to call explicitly.
  • For constructor , you can give four access modifiers public , protected, private , default(without specifying).
  • If you give public to constructor, You can create object for that class in the same class and from any class of any package.
  • If you give protected to constructor, You can create object for that class in the same class and from all classes of same package and from sub classes of other packages.
  • If you give default to constructor(none is specified), You can create object for that class in the same class and from all classes of same package and you can’t create from classes of other packages.
  • If you give private to constructor, You can create object for that class in the same class and you can’t create from classes of same or other packages.
  • A constructor is used to initialize instance variables

Example :

public class Test {
	private int value1;
	private int value2;

	Test(int value1, int value2) {
		this.value1 = value1;
		this.value2 = value2;
	}

	public static void main(String[] args) {
		Test t = new Test(7, 8);
		System.out.println(t.value1 + " " + t.value2);// prints 7 8
	}

}
  • In the above example this is used to call instance variables of class.You can omit this if instance variable name and constructor parameter name are different

Default Constructor

When you don’t create any constructor, then Java insert a constructor without any parameters. That constructor will be called as Default Constructor.

Let us see example how Java inserted constructor looks like

Example :

//The below is the program you typed
public class Test {

	public static void main(String[] args) {
		Test t = new Test();

	}

}


//The below is the program at the time of compilation
public class Test {

	public Test() {
		super();
	}
	public static void main(String[] args) {
		Test t = new Test();

	}

}

  • Observe the above program, How Java inserted constructor looks like
  • The constructor contains no parameters.
  • Access modifier of constructor and class is same.
  • There is super() statement which calls super class No argument constructor.
  • Below is the program to illustrate super() statement.

Example :

public class Test1 extends Test2 {

	public static void main(String[] args) {
		Test1 t = new Test1();

	}

}

class Test2 {
	Test2() {
		System.out.println("OCAJP");
	}
}

It outputs like

OCAJP

What is constructor overloading?

  • You can overload a constructor like you overload a method
  • Every constructor name must be same. Generally constructors names will be same because constructor name is same class name
  • All constructors parameters should be different
  • The difference in constructors parameters can be number of parameters, data types of parameters, order of parameters

Example :

public class Test {

	Test() {
		System.out.println("no argument constructor");
	}

	public Test(int a) {
		System.out.println("one argument constructor: " + a);
	}

	protected Test(int x, char y) {
		System.out.println("one argument constructor: " + x + " " + y);
	}

	private Test(char x, int y) {
		System.out.println("one argument constructor: " + x + " " + y);
	}

	public static void main(String[] args) {

		Test t1 = new Test();
		Test t2 = new Test(2);
		Test t3 = new Test(3, 'a');
		Test t4 = new Test('b', 7);
	}

}

It outputs like

no argument constructor
one argument constructor: 2
one argument constructor: 3 a
one argument constructor: b 7
  • In the above program there are total four constructors.
  • All constructors parameters are different and access modifiers can be different.
  • If a class has a private constructor, you create object for that class within class. You can’t create object in other classes
  • When you are creating object for a class the class must have appropriate constructor other wise you get compile time error

Example :

public class Test {
	 Test(int a) {
		System.out.println("one argument constructor: " + a);
	}

	public static void main(String[] args) {

		Test t = new Test(2,3);//compile time error at this line
	}

}

Conclusion

We hope this article would have provided good idea on how to use the constructors and how to overload them. This concepts are very much tested in the OCAJP exam questions. Please remember to take notes on each topic and memorize the important concepts before you plan at attend the real exam. You should be able identify when default constructor will be created , constructor with return type. When you see object created for a class see the constructors list in class( and in super class also, if present).

Practice Questions

It is important to practice more number of questions for preparing for the OCA Java certification exam. We have prepared 600+ high quality questions that covers all the exam objectives and provides explanation for all the option given for the question. This would help you to improve our confidence on the exam before you are taking the real exam.

Technical Support

If you are looking for any technical support like more explanation on each questions or clarifications, we have a dedicated support for Java certification to answer all your queries. You can drop us a mail at info@whizlabs.com with your queries. We would respond to your questions within 12 hours of time.

Good luck for your exam preparation!!

About Aditi Malhotra

Aditi Malhotra is the Content Marketing Manager at Whizlabs. Having a Master in Journalism and Mass Communication, she helps businesses stop playing around with Content Marketing and start seeing tangible ROI. A writer by day and a reader by night, she is a fine blend of both reality and fantasy. Apart from her professional commitments, she is also endearing to publish a book authored by her very soon.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top