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.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several