devxlogo

Use an Interface to Provide Classes with Constant Value(s)

Use an Interface to Provide Classes with Constant Value(s)

If you have two or more classes that need to share some constant value(s), but you want the classes to be independent of each other, define the constant values in an interface. You can then implement the interface in both classes instead of using a static variable. The following example illustrates the use of a static variable, which is the most common approach:

 public class A {	public static String NAME = "Java Pro";	public A() {		System.out.println("Subscribe to " + NAME);	}}public class B {	public B() {		System.out.println("Renew your subscription to " +A.NAME);	}}

The problem with this technique is that the two classes (A and B) are not independent. Class A may not contain any methods that B requires, and in fact may be a completely unrelated class. But Class A must still be present for B to function correctly, making B less portable. Alternatively, you can use an interface as follows:

 public interface Names {	public static String NAME = "Java Pro";}public class A implements Names {	public A() {		System.out.println("Subscribe to " + NAME);	}}public class B implements Names {	public B() {		System.out.println("Renew your subscription to " +NAME);	}}

The interface doesn’t even need to have any methods defined for it; it can exist solely to provide classes with the constant value(s). This enhances their portability, since there are no explicit references to or dependencies on external classes.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist