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:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS