class
Conflicting Constructors
With this example we are going to demonstrate how to use conflicting constructors in a class. In short, to use conflicting constructors in a class we have followed the steps below:
- We have created a class
ConflictingConstructors
, that has a constructor without fields and a constructor that gets an int value and throws an IllegalArgumentException if it is smaller than0
. It also has avoid Constructor()
method and another method,method1()
. - We create a new instance of
ConflictingConstructors
, using its first constructor and then call itsmethod1()
method. - We also call its
Constructor()
method. - We create a new instance of the class, using its second constructor with a value smaller than zero to see that the exception is now thrown.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; public class ConflictingConstructors { /** * Constructor */ public ConflictingConstructors() { System.out.println("In the constructor"); } /** * Constructor that throws */ public ConflictingConstructors(int value) { if (value < 0) { throw new IllegalArgumentException("Constructors: value < 0"); } } /** * Not a Constructor, because of void */ public void Constructors() { // EXPECT COMPILE ERROR some compilers System.out.println("In void Constructor()"); } void method1() { for (int i = 0; i < 5; i++) { System.out.println(i); } } public static void main(String[] a) { ConflictingConstructors l = new ConflictingConstructors(); l.method1(); l.Constructors(); new ConflictingConstructors(-1); // expect Exception } }
Output:
In the constructor
0
1
Exception in thread "main" java.lang.IllegalArgumentException: Constructors: value < 0
2
3
4
In void Constructor()
at methodoverloading.ConflictingConstructors.<init>(ConflictingConstructors.java:17)
at methodoverloading.ConflictingConstructors.main(ConflictingConstructors.java:38)
Java Result: 1
This was an example of how to use conflicting constructors in a class in Java.