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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date