Unit - IV Packages
Unit - IV Packages
Unit - IV Packages
package pack1;
public interface myDate
{
void showDate();
}
• The Java compiler creates a sub directory with the name pack1 and
stores myDate.class file there.
• This myDate.class file denotes the bytecode of the interface.
• The next step is to create the implementation class for myDate
interface where showDate() method body should be written.
• DateImpl is an implementation class where the body for showDate()
method is written.
• We create an object to Dateclass of java.util package which by default
stores the system date and time.
package pack1;
import pack1.myDate;
import java.util.*;
public class DateImpl implements
myDate
{
public void showDate()
{
Date d=new Date();
System.out.println(d);
}
}
• When the preceding code is import pack1.DateImpl;
compiled DateImpl.class file is class DateDisplay
created in the same package
pack1. {
• DateImpl class contains public static void main(String
showDate() method which can be args[])
called and used in any other {
program.
DateImpl obj=new DateImpl();
• DateDisplay is the class where we
want to use DateImpl class. obj.showDate();
• So object to DateImpl is created }
and the showDate() method is }
called.
• This displays system date and time.
Creating subpackage in a package
• We can create a subpackage in a package in the format
• Package pack1.pack2;
• Here we are creating pack2 which is created inside pack1.
• To use the classes and interfaces of pack2 we can write import
statement as
• Import pack1.pack2;
• This concept can be extended to create several sub packages.
package pack3.pack4;
class sample
{
public void show()
{
System.out.println("Welcome");
}
}
import pack3.pack4.sample;
class sample1
{
public static void main(String args[])
{
sample obj=new sample();
obj.show();
}
}
Scope of the members in package
package same;
public class access
{
private int a=1;
public int b=2;
protected int c=3;
int d=4;
}
package same;
import same.access;
public class Baccess
{
public static void main(String args[])
{
access obj=new access();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
package another;
import same.access;
public class Caccess
{
public static void main(String args[])
{
access obj=new access();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
package another;
import same.access;
public class C extends access
{
public static void main(String args[])
{
C obj=new C();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}