HowTo JAVA-2:Importing class and packages
This time I`ll to to keep some points in my mind bout importing.
Why should we import?
Obviously its because of code reusing.Java is,infact 70% depends on API and its nothing but code reusing.We use java.util.* Wat does it mean ? It means just find out any specific class inside the package java.util. And that class may be Vector class or any other class.
See the following code
import java.util.*;
class UseVector
{
public static void main(String[] args)
{
Vector v = new Vector();
for (int i = 0; i < 10; ++i)
v.addElement(new Integer(i));
for (int i = 0; i < v.size(); ++i)
System.out.print(v.elementAt(i) + " ");
}
}
We created an instance v of type vector .But where from we got that vector class.Surely it comes from the package
java.util.*
Vector is nothing but a container.Its containing.Well I`ll discuss bout Vector some other day.
Wats that ".*" do?
Nothing,If we import a package with the ".*" ,then it opens a package for name lookup, so when the javac translator can’t find a name in the current directory, it looks in the package java.util to find it.
But wat if we have a Vector class in the current directory?Then the javac will not bother bout that "util" brother at all.It will just pick the current one.So cleaver na?
K.But u`ll say I am alsoa sticky gum.I will make that smart javac to pick that one from the 'util" brother evenif there is one Vector class inside the current directory. Hmmmmm....Then you have two options
1>You can change the import statement to explicitly associate the name Vector with java.util.Vector, as follows:
import java.util.Vector;
2>or, you can use a fully qualified class name and ignore the import altogether:
// Note: no import statement
class UseVector
{
public static void main(String[] args)
{
java.util.Vector v = new java.util.Vector();
.......
............
...........
........
}
Well....I am getting boredddddd.......I`ll post one more on holi and then I`ll go back room.
Labels: Technical_HowTo_Java
0 Comments:
Post a Comment
<< Home