Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Nov 19, 1998

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.
Brett Spell
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap