WHAT'S NEW?

Importing classes in Java and making it accessible (OCAJP 1.4)

Import Statement in Java.


Package is the collection of classes and interfaces in some directorial hierarchy.

Java have packaged all its classes and interface in a library structure.

Whole Java library is bundled in a jar file by name rt.jar which resides in jre folder where Java is installed.
If we extract rt.jar we will find some of the





Now for using this classes we need to use import statement of Java.

Let us have a look at the code snippet below.

import java.util.*;

public class ShowDate
{
public static void main(String[] args)
{
Date dt=new Date();
System.out.println("Today's Date:"+dt);
}
}


Now if we try to understand its working, when the file is compiled it tries to search for the files in the following way.



1. It tries to search it in the same folder, that is the reason why two java files in same folder can access each other.2. If not found it tries to search it in java.lang package.3. If it is not found in java.lang package it tries to search it in any imported package, if found uses it or throw an error.



Packages system was created to manage the confusion in the naming systems.
But sometime it can too create a confusion.

For example let say, if a java file uses class Date and two packages java.sql and java.util both are imported, then the compiler gets confused

DateAmbiguity.java

import java.util.*;

import java.sql.*;



class DateAmbiguity

{

 public static void main(String[] args)

 {

  Date dt=new Date();

 }

}



How to solve the ambiguity problem?

When stuck in such a situation, we can use qualified import for defining the exact class. Modified code will look like.


DateAmbiguity.java (Modified)



class DateAmbiguity 
{
public static void main(String[] args) 
{
java.util.Date utDt=new java.util.Date();
java.sql.Date sqDt=new java.sql.Date(2016,2,2);
}
}

How to import classes which are inside package which is itself inside a package?

There can be instances where we need to use the class or interface which resides into the package which itself is inside another package.
For example ActionListener interface resides in package java which have another package awt which have another package event.
java>awt>event>ActionListener.java

Remember when we import a package we only import the classes and interfaces within  it and not the other packages and their classes and interfaces.
So we need to import other packages separately.

For example

import java.aw.event.*;



class MyClass implements ActionListener

{

 public void actionPerformed(ActionEvent ae)

 {

 }

} 

0 comments:

Post a Comment