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 than 0. It also has a void Constructor() method and another method, method1().
  • We create a new instance of ConflictingConstructors, using its first constructor and then call its method1() 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button