|
|
YOUR FEEDBACK
Did you read today's front page stories & breaking news?
SYS-CON.TV |
TOP THREE LINKS YOU MUST CLICK ON Hot Story
Java Basics: Lesson 11, Java Packages and Imports (Live Video Education)
Lesson 11 in the Hugely Popular "Java Basics" Series by JDJ Editorial Board Member Yakov Fain
By: Yakov Fain
Digg This!
Page 3 of 3
« previous page
Java 5.0 has introduced a new element called static imports. While regular import statements allow you to use the class name without specifying its package name, static imports go further and allow using static members of another class without specifying their class name. Let's use our good old HelloWorld program as an example: Based on this syntax, we can guess that there is a static variable out in the class System that represents some object that in turn has a static method println(). Let's add the static import to eliminate the need of specifying the name of the class System in front of the variable out: You do not have to use the wildcard (*) and import all static members from a class, but rather specific ones, for example or for the PI constant from the Math package it can look like this: For example: The good news is that if you need to call the println() method multiple times, your program becomes shorter now. The bad side effect of static imports is that if you'll start overusing this feature, pretty soon your program will actually become less readable. For example, if you'll use static imports of multiple constants from various packages, and someone else (or even yourself five months later) will need to read this program, it may become difficult to understand where all these constants are coming from, especially if you've been using wildcards. The last HelloWorld example gives you an impression that PI constant has been declared somewhere in the HelloWorld class itself. In a small program it's easy to see that this is not the case, but in more complex applications consisting of hundreds of classes this can cause unnecessary confusions. Prior to Java 5.0 you could have created Java interfaces containing only final static variables, for example Now any class that implements MyConstants can use this variables without even mentioning the name of the interface: Strictly speaking, if a class implements an interface, you'd expect it to implement some behavior which is not the case in the above example. That's why it's not a recommended way of using interfaces. Oh well, unless you have multiple interfaces with hundreds of constants, I do not see any damage in use of static imports or constant-only interfaces. Page 3 of 3 « previous page
BEA WEBLOGIC LATEST STORIES
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
|
SYS-CON FEATURED WHITEPAPERS MOST READ THIS WEEK BREAKING NEWS FROM THE WIRES |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||