SlideShare a Scribd company logo
UNIT-IV

                               PACKAGES AND INTERFACES

DEFINING PACKAGE:

This chapter examines two of Java‟s most innovative features: packages and interfaces.
Packagesare containers for classes that are used to keep the class name
spacecompartmentalized. Packages are stored in a hierarchical manner andare explicitly
imported into new class definitions.
A package is a container of classes and interfaces. A package represents a directory that contains
related group of classes and interfaces. For example, when we write statemens like:
import java.io.*;
Here we are importing classes of java.io package. Here, java is a directory name and io is another
sub directory within it. The „*‟ represents all the classes and interfaces of thatio sub directory.
We can create our own packages called user-defined packages or extend the available packages.
User-defined packages can also be imported into other classes and used exactly in the same way
as the Built-in packages.
USE: Packages provide reusability.

ADVANTAGES OF PACKAGES:
     Packages are useful to arrange related classes and interfaces into a group. This makes all
      the classes and interfaces performing the same task to put together in the same
      package.For example , in Java, all the classes and interfaces which perform input and
      output operations are stored in java.io. package.
     Packages hide the classes and interfaces in a separate sub directory, so that accidental
      deletion of classes and interfaces will not take place.
     The classes and interfaces of a package are isolated from the classes and interfaces of
      another package. This means that we can use same names for classes of two different
      classes. For example, there is a Date class in java.util package and also there is another
      Date class in java.sql package.
     A group of package called a library. The classes and interfaces of a package are likes
      books in a library and can be reused several times. This reusability nature of packages
      makes programming easy. Just think, the package in Java are created by JavaSoft people
      only once, and millions of programmers all over the world are daily by using them in
      various programs.

Different Types of Packages:
There are two types of packages in Java. They are:
      Built-in packages
      User-defined packages
Built-in packages:
These are the packages which are already available in Java language. These packages provide all
most all necessary classes, interfaces and methods for the programmer to perform any task in his
programs. Since, Java has an extensie library of packages, a programmer need not think about
logic for doing any task. For everything, there is a method available in Java and that method can
be used by the programmer without developing the logic on his own. This makes the
programming easy. Here,we introduce some of the important packages of Java SE:
Java.lang: lang stands for language. This package got primary classes and interfaces essential for
developing a basic Java program. It consists of wrapper classes(Integer, Character, Float etc),
which are useful to convert primitive data types into objects. There are classes like String,
SttringBuffer, StringBuilder classes to handle strings. There is a thread class to create various
individual processes. Runtime and System classes are also present in java.lang package which
contain methods to execute an application and find the total memory and free memory available
in JVM.
Java.util: util stands for utility. This package contains useful classes and interfaces like Stack,
LinkedList, Hashtable, Vector, Arrays, etc. thses classes are collections. There are also classes
for handling Date and Time operations.
Java.io: io stands for input and output. This package contains streams. A stream represents flow
of data from one place to another place. Streams are useful to store data in the form of files and
also to perform input-output related tasks.
Java.awt: awt stands for abstract window toolkit. This helps to develop GUI(Graphical user
Interfaces) where programs with colorful screens, paintings and images etc., can be developed. It
consists of an important sub package, java.awt.event, which is useful to provide action for
components like push buttons, radio buttons, menus etc.
Javax.swing: this package helps to develop GUI like java.awt. The „x‟ in javax represents that it
is an extended package which means it is a package developed from another package by adding
new features to it. In fact, javax.swing is an extended package of java.awt.
Java.net: net stands for network. Client-Server programming can be done by using this package.
Classes related to obtaining authentication for network, creating sockets at client and server to
establish communication between them are also available in java.net package.
Java.applet: applets are programs which come from a server into a client and get executed on the
client machine on a network. Applet class of this package is useful to create and use applets.
Java.text: this package has two important classes, DateFormat to format dates and times, and
NumberFormat which is useful to format numeric values.
Java.sql: sql stands structured query language. This package helps to connect to databases like
Oracle or Sybase, retrieve the data from them and use it in a Java program.
Unit4 java
Unit4 java
User-Defined packages:
Just like the built in packages shown earlier, the users of the Java language can also create their
own packages. They are called user-defined packages. User-defined packages can also be
imported into other classes and used exactly in the same way as the Built-in packages.
CREATING AND IMPORTING PACKAGES:

packagepackagename; //to create a package
packagepackagename.subpackagename;//to create a sub package within a package.
e.g.: package pack;
       The first statement in the program must be package statement while creating a package.
       While creating a package except instance variables, declare all the members and
        the class itself as public then only the public members are available outside the
        package to other programs.
Program 1: Write a program to create a package pack with Addition class.
//creating a package
package pack;
public class Addition
{ private double d1,d2;
public Addition(double a,double b)
{ d1 = a;
     d2 = b;
 }
public void sum()
{ System.out.println ("Sum of two given numbers is : " + (d1+d2) );
 }
}
Compiling the above program:




The –d option tells the Java compiler to create a separate directory and place the .class file in that
directory (package). The (.) dot after –d indicates that the package should be created in
the current directory. So, out package pack with Addition class is ready.
Program 2: Write a program to use the Addition class of package pack.
//Using the package pack
importpack.Addition;
class Use
{ public static void main(String args[])
{ Addition ob1 = new Addition(10,20);
ob1.sum();
    }
}
Output:




Program 3: Write a program to add one more class Subtraction to the same package pack.
//Adding one more class to package pack:
package pack;
public class Subtraction
{ private double d1,d2;
public Subtraction(double a, double b)
{ d1 = a;
d2 = b;
    }
public void difference()
{ System.out.println ("Sum of two given numbers is : " + (d1 - d2) );
    }
}
Compiling the above program:




Program 4: Write a program to access all the classes in the package pack.
//To import all the classes and interfaces in a class using import pack.*;
import pack.*;
class Use
{ public static void main(String args[])
{ Addition ob1 = new Addition(10.5,20.6);
ob1.sum();
        Subtraction ob2 = new Subtraction(30.2,40.11);
ob2.difference();
    }
}
In this case, please be sure that any of the Addition.java and Subtraction.java programs will not
exist in the current directory. Delete them from the current directory as they cause confusion for
the Java compiler. The compiler looks for byte code in Addition.java and Subtraction.java files
and there it gets no byte code and hence it flags some errors.
UNDERSTANDING CLASSPATH:

If the package pack is available in different directory, in that case the compiler should be given
information regarding the package location by mentioning the directory name of the package in
the classpath.
The CLASSPATH is an environment variable that tells the Java compiler where to look for
class files to import.
If our package exists in e:sub then we need to set class path as follows:




 We are setting the classpath to e:sub directory and current                      directory   (.)
an%CLASSPATH% means retain the already available classpath as it is.
Creating Sub package in a package: We can create sub package in a package in the format:
packagepackagename.subpackagename;
 e.g.: package pack1.pack2;
Here, we are creating pack2 subpackage which is created inside pack1 package. To use
the classes and interfaces of pack2, we can write import statement as:
import pack1.pack2;
Program 5: Program to show how to create a subpackage in a package.
//Creating a subpackage in a package
package pack1.pack2;
public class Sample
{ public void show ()
 {
System.out.println ("Hello Java Learners");
 }
}
Compiling the above program:




ACCESSING A PACKAGES:
Access Specifier: Specifies the scope of the data members, class and methods.
     private members of the class are available with in the class only. The scope of
      private members of the class is “CLASS SCOPE”.
     public members of the class are available anywhere . The scope of public members of
      the class is "GLOBAL SCOPE".
     default members of the class are available with in the class, outside the class and in its
      sub class of same package. It is not available outside the package. So the scope
      of default members of the class is "PACKAGE SCOPE".
     protected members of the class are available with in the class, outside the class and in its
      sub class of same package and also available to subclasses in different package also.




Program 6: Write a program to create class A with different access specifiers.
//create a package same
package same;
public class A
{ privateint a=1;
publicint b = 2;
protectedint c = 3;
int d = 4;
}
Compiling the above program:




Program 7: Write a program for creating class B in the same package.
//class B of same package
package same;
importsame.A;
public class B
{
public static void main(String args[])
    {
A obj = new A();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
    }
}
Compiling the above program:




Program 8: Write a program for creating class C of another package.
package another;
importsame.A;
public class C extends A
{ public static void main(String args[])
{ Cobj = new C();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
    }
}


Compiling the above program:




DIFFERENCES BETWEEN CLASSES AND INTERFACES:

Classes                                        Interfaces
Classes have instances as variables and        Interfaces have instances as abstract methods
methods with body                              and final constants variables.
Inheritance goes with extends keyword          Inheritance goes with implements keywords.
The variables can have any acessspecifier.     The Variables should be public, static, final
Multiple inheritance is not possible           It is possible
Classes are created by putting the keyword     Interfaces are created by putting the keyword
class prior to classname.                      interface prior to interfacename(super class).
Classes contain any type of methods. Classes   Interfaces contain mustly abstract methods.
may or may not provide the abstractions.       Interfaces are exhibit the fully abstractions
DEFINING AN INTERFACE AND IMPLEMENTING AN INTERFACE :

A programmer uses an abstract class when there are some common features shared by all
the objects. A programmer writes an interface when all the features have different
implementations for different objects. Interfaces are written when the programmer wants
to leave the implementation to third party vendors. An interface is a specification of method
prototypes. All the methods in an interface are abstract methods.
            An interface is a specification of method prototypes.
            An interface contains zero or more abstract methods.
            All the methods of interface are public, abstract by default.
            An interface may contain variables which are by default public static final.
            Once an interface is written any third party vendor can implement it.
            All the methods of the interface should be implemented in its implementation classes.
             If any one of the method is not implemented, then that implementation class
             should be declared as abstract.
             We cannot create an object to an interface.
             We can create a reference variable to an interface.
            An interface cannot implement another interface.
            An interface can extend another interface.
            A class can implement multiple interfaces.
An interface is defined much like a class. This is the general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create the
methods defined by the interface. The general form of a class that includes the implements clause
looks like this:
classclassname [extends superclass] [implements interface [,interface...]] {
// class-body
}
If a class implements more than one interface, the interfaces are separated with a comma. If a
class implements two interfaces that declare the same method, then the same method will be used
by clients of either interface. The methods that implement an interface must be declared public.
Also, the type signature of the implementing method must match exactly the type signature
specified in the interface definition.
Partial Implementations
If a class includes an interface but does not fully implement the methods defined by that
interface, then that class must be declared as abstract. For example:
abstract class Incomplete implements Callback {
int a, b;
void show() {
System.out.println(a + " " + b);
}
// ...
}
Here, the class Incomplete does not implement callback( ) and must be declared as abstract.
Any class that inherits Incomplete must implement callback( ) or be declared abstract itself.
Nested Interfaces
An interface can be declared a member of a class or another interface. Such an interface is
called a member interface or a nested interface. Anested interface can be declared as public,
private, or protected. This differs from a top-level interface, which must either be declared
as public or use the default access level, as previously described. When a nested interface is
used outside of its enclosing scope, it must be qualified by the name of the class or interface
of which it is a member. Thus, outside of the class or interface in which a nested interface is
declared, its name must be fully qualified.
Here is an example that demonstrates a nested interface:
// A nested interface example.
// This class contains a member interface.
class A {
// this is a nested interface
public interface NestedIF {
booleanisNotNegative(int x);
}
}
// B implements the nested interface.
class B implements A.NestedIF {
publicbooleanisNotNegative(int x) {
return x < 0 ? false : true;
}
}
classNestedIFDemo {
public static void main(String args[]) {
// use a nested interface reference
A.NestedIFnif = new B();
if(nif.isNotNegative(10))
System.out.println("10 is not negative");
if(nif.isNotNegative(-12))
System.out.println("this won't be displayed");
}
}
Notice that A defines a member interface called NestedIFand that it is declared public. Next, B
implements the nested interface by specifying implements
A.NestedIF
Notice that the name is fully qualified by the enclosing class‟ name. Inside the main( )method, an
A.NestedIF reference called nif is created, and it is assigned a reference to a B object. Because B
implements A.NestedIF, this is legal.
Program 1: Write an example program for interface
interface Shape
{ void area ();
void volume ();
double pi = 3.14;
}
class Circle implements Shape
{ double r;
    Circle (double radius)
{ r = radius;
    }
public void area ()
{ System.out.println ("Area of a circle is : " + pi*r*r );
    }
public void volume ()
{ System.out.println ("Volume of a circle is : " + 2*pi*r);
    }
}
class Rectangle implements Shape
{ doublel,b;
    Rectangle (double length, double breadth)
{ l = length;
        b = breadth;
    }
public void area ()
{ System.out.println ("Area of a Rectangle is : " + l*b );
    }
public void volume ()
{ System.out.println ("Volume of a Rectangle is : " + 2*(l+b));
    }
}
classInterfaceDemo
{ public static void main (String args[])
{ Circle ob1 = new Circle (10.2);
        ob1.area ();
        ob1.volume ();
        Rectangle ob2 = new Rectangle (12.6, 23.55);
        ob2.area ();
        ob2.volume ();
    }
}
Output:




APPLYING INTERFACE:

To understand the power of interfaces, let‟s look at a more practical example. In earlierchapters,
you developed a class called Stack that implemented a simple fixed-size stack.However, there
are many ways to implement a stack. For example, the stack can be of afixed size or it can be
“growable.” The stack can also be held in an array, a linked list, abinary tree, and so on. No
matter how the stack is implemented, the interface to the stackremains the same. That is, the
methods push( ) and pop( ) define the interface to the stackindependently of the details of the
implementation. Because the interface to a stack isseparate from its implementation, it is easy to
define a stack interface, leaving it to eachimplementation to define the specifics. Let‟s look at
two examples.
First, here is the interface that defines an integer stack. Put this in a file called IntStack.java.
This interface will be used by both stack implementations.
// Define an integer stack interface.
interfaceIntStack {
void push(int item); // store an item
int pop(); // retrieve an item
}
Applications are:
       Abstractions
       Multiple Inheritance

VARIABLES IN INTERFACES:

You can use interfaces to import shared constants into multiple classes by simply declaringan
interface that contains variables that are initialized to the desired values. When youinclude that
interface in a class (that is, when you “implement” the interface), all of thosevariable names will
be in scope as constants. (This is similar to using a header file in C/C++to create a large number
of #defined constants or const declarations.) If an interface containsno methods, then any class
that includes such an interface doesn‟t actually implement anything.
It is as if that class were importing the constant fields into the class name space as finalvariables.
The next example uses this technique to implement an automated “decision maker”:
importjava.util.Random;
interfaceSharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
class Question implements SharedConstants {
Random rand = new Random();
int ask() {
intprob = (int) (100 * rand.nextDouble());
if (prob< 30)
return NO;           // 30%
else if (prob< 60)
return YES;          // 30%
else if (prob< 75)
return LATER;          // 15%
else if (prob< 98)
return SOON;          // 13%
else
return NEVER;          // 2%
}
}
classAskMe implements SharedConstants {
static void answer(int result) {
switch(result) {
case NO:
System.out.println("No");
break;
case YES:
System.out.println("Yes");
break;
case MAYBE:
System.out.println("Maybe");
break;
case LATER:
System.out.println("Later");
break;
case SOON:
System.out.println("Soon");
break;
case NEVER:
System.out.println("Never");
break;
}
}
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}
Notice that this program makes use of one of Java‟s standard classes: Random. This class
provides pseudorandom numbers. It contains several methods that allow you to obtain random
numbers in the form required by your program. In this example, the method nextDouble( ) is
used. It returns random numbers in the range 0.0 to 1.0.
In this sample program, the two classes, Question and AskMe, both implement the
SharedConstants interface where NO, YES, MAYBE, SOON, LATER, and NEVER are defined.
Inside each class, the code refers to these constants as if each class had defined or inherited them
directly. Here is the output of a sample run of this program. Note that the results are different
each time it is run.
Later
Soon
No
Yes
EXTENDING INTERFACES:

One interface can inherit another by use of the keyword extends. The syntax is the same as
for inheriting classes. When a class implements an interface that inherits another interface,
it must provide implementations for all methods defined within the interface inheritance
chain. Following is an example:
// One interface can extend one or more interfaces..
interface A {
void meth1();
void meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and B
classMyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
classIFExtend {
public static void main(String arg[]) {
MyClassob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
As an experiment, you might want to try removing the implementation for meth1( ) in MyClass.
This will cause a compile-time error. As stated earlier, any class that implements an interface
must implement all methods defined by that interface, including any that are inherited from other
interfaces.
Although the examples we‟ve included in this book do not make frequent use of packages or
interfaces, both of these tools are an important part of the Java programming environment.
Virtually all real programs that you write in Java will be contained within packages. A number
will probably implement interfaces as well. It is important, therefore, that you be comfortable
with their usage.

EXPLORING JAVA.IO.*;

A Stream represents flow of data from one place to another place. Input Streams reads or accepts
data. Output Streams sends or writes data to some other place. All streams are represented as
classes in java.io package. The main advantage of using stream concept is to achieve hardware
independence. This is because we need not change the stream in our program even though we
change the hardware. Streams are of two types in Java:

Streams
Java programs perform I/O through streams. Astream is an abstraction that either produces or
consumes information. A stream is linked to a physical device by the Java I/O system.
All streams behave in the same manner, even if the actual physical devices to which they are
linked differ. Thus, the same I/O classes and methods can be applied to any type of device. This
means that an input stream can abstract many different kinds of input: from a disk file, a
keyboard, or a network socket. Likewise, an output stream may refer to the console, a disk file,
or a network connection.
Streams are a clean way to deal with input/output withouthaving every part of your code
understand the difference between a keyboard and a network,for example. Java implements
streams within class hierarchies defined in the java.io package.
     Byte Streams: Handle data in the form of bits and bytes. Byte streams are used to handle
      any characters (text), images, audio and video files. For example, to store an image
file (.gif or .jpg), we should go for a byte stream. To handle data in the form of
'bytes' the abstract classes: InputStream and OutputStream are used. The important
classes of byte streams are:
Unit4 java
 BufferedReader/BufferedWriter: - Handles characters (text) by buffering them. They
     provide efficiency.
    CharArrayReader/CharArrayWriter: - Handles array of characters.
    InputStreamReader/OutputStreamWriter: - They are bridge between byte streams
     and character streams. Reader reads bytes and then decodes them into 16-bit
     unicodecharacters. Writer decodes characters into bytes and then writes.
    PrintReader/PrintWriter: - Handle printing of characters on the screen.
File: A file represents organized collection of data. Data is stored permanently in the file. Once
data is stored in the form of a file we can use it in different programs.
   Program 1: Write a program to read data from the keyboard and write it to a text file using
   byte
   stream classes.
   //Creating a text file using byte stream classes
   import java.io.*;
   class Create1
   { public static void main(String args[]) throws IOException
   { //attach keyboard to DataInputStream
   DataInputStream dis = new DataInputStream (System.in);
      //attach the file to FileOutputStream
   FileOutputStreamfout = new FileOutputStream ("myfile");
//read data from DataInputStream and write into FileOutputStream
charch;
System.out.println ("Enter @ at end : " ) ;
while( (ch = (char) dis.read() ) != '@' )
fout.write (ch);
fout.close ();
    }
}
Output:




Program 2: Write a program to improve the efficiency of writing data into a file
using BufferedOutputStream.
//Creating a text file using byte stream classes
import java.io.*;
class Create2
{ public static void main(String args[]) throws IOException
{ //attach keyboard to DataInputStream
DataInputStream dis = new DataInputStream (System.in);
        //attach file to FileOutputStream, if we use true then it will open in append mode
FileOutputStreamfout = new FileOutputStream ("myfile", true);
BufferedOutputStream bout = new BufferedOutputStream (fout, 1024);
//Buffer size is declared as 1024 otherwise default buffer size of 512 bytes is used.
        //read data from DataInputStream and write into FileOutputStream
charch;
System.out.println ("Enter @ at end : " ) ;
while ( (ch = (char) dis.read() ) != '@' )
bout.write (ch);
bout.close ();
fout.close ();
    }
}
OUTPUT:




Program 3: Write a program to read data from myfile using FileInputStream.
//Reading a text file using byte stream classes
import java.io.*;
class Read1
{ public static void main (String args[]) throws IOException
{ //attach the file to FileInputStream
FileInputStream fin = new FileInputStream ("myfile");
        //read data from FileInputStream and display it on the monitor
intch;
while ( (ch = fin.read() ) != -1 )
System.out.print ((char) ch);
fin.close ();
}
}
Output:




Program 4: Write a program to improve the efficiency while reading data from a file
using
BufferedInputStream.
//Reading a text file using byte stream classes
import java.io.*;
class Read2
{ public static void main(String args[]) throws IOException
{ //attach the file to FileInputStream
FileInputStream fin = new FileInputStream ("myfile");
BufferedInputStream bin = new BufferedInputStream (fin);
        //read data from FileInputStream and display it on the monitor
intch;
while ( (ch = bin.read() ) != -1 )
System.out.print( (char) ch);
fin.close ();
    }
}
Output:
Program 5: Write a program to create a text file using character or text stream classes.
//Creating a text file using character (text) stream classes
import java.io.*;
class Create3
{ public static void main(String args[]) throws IOException
{ Stringstr = "This is an Institute" + "n You are a student";   // take a String
        //Connect a file to FileWriter
FileWriterfw = new FileWriter ("textfile");
        //read chars from str and send to fw
for (inti = 0; i<str.length () ; i++)
fw.write (str.charAt (i) );
fw.close ();
    }
}
Output:




Program 6: Write a program to read a text file using character or text stream classes.
//Reading data from file using character (text) stream classes
import java.io.*;
class Read3
{ public static void main(String args[]) throws IOException
{ //attach file to FileReader
FileReaderfr = new FileReader ("textfile");
        //read data from fr and display
intch;
while ((ch = fr.read()) != -1)
System.out.print ((char) ch);
        //close the file
fr.close ();
    }
}
Output:




Note: Use BufferedReader and BufferedWriter to improve the efficiency of the above
two programs.
Serialization of objects:
             Serialization is the process of storing object contents into a file. The class whose
              objects are stored in the file should implement "Serializable' interface of java.io
              package.
             Serializable interface is an empty interface without any members and methods,
              such an interface is called 'marking interface' or 'tagging interface'.
             Marking interface is useful to mark the objects of a class for a special purpose. For
              example, 'Serializable' interface marks the class objects as 'serializable' so that they
              can be written into a file. If serializable interface is not implemented by the class,
              then writing that class objects into a file will lead to NotSerializableException.
             static and transient variables cannot be serialized.
             De-serialization is the process of reading back the objects from a file.


Program 7: Write a program to create Employ class whose objects is to be stored into a file.
//Employ information
import java.io.*;
importjava.util.*;
class Employ implements Serializable
{ privateint id;
private String name;
private float sal;
private Date doj;
    Employ (inti, String n, float s, Date d)
{ id = i;
name = n;
sal = s;
doj = d;
    }
void display ()
    {
System.out.println (id+ "t" + name + "t" + sal + "t" + doj);
}
static Employ getData() throws IOException
{ BufferedReaderbr = new BufferedReader (new InputStreamReader (System.in));
System.out.print ("Enter employ id : ");
int id = Integer.parseInt(br.readLine());
System.out.print ("Enter employ name : ");
String name = br.readLine ();
System.out.print ("Enter employ salary : " );
floatsal = Float.parseFloat(br.readLine ());
Date d = new Date ();
Employ e = new Employ (id, name, sal, d);
return e;
}
}




Program 8: Write a program to show serialization of objects.
//ObjectOutputStream is used to store objects to a file
import java.io.*;
importjava.util.*;
classStoreObj
{ public static void main (String args[]) throws IOException
{ BufferedReaderbr = new BufferedReader (new InputStreamReader (System.in));
FileOutputStreamfos = new FileOutputStream ("objfile");
ObjectOutputStreamoos = new ObjectOutputStream( fos );
System.out.print ("Enter how many objects : ");
int n = Integer.parseInt(br.readLine () );
for(inti = 0;i<n;i++)
{ Employ e1 = Employ.getData ();
oos.writeObject (e1);
        }
oos.close ();
fos.close ();
    }
}
Output:
Program 9: Write a program showing deserialization of objects.
//ObjectInputStream is used to read objects from a file
import java.io.*;
classObjRead
{ public static void main(String args[]) throws Exception
 {
FileInputStreamfis = new FileInputStream ("objfile");
ObjectInputStreamois = new ObjectInputStream (fis);
try
{ Employ e;
while ( (e = (Employ) ois.readObject() ) != null)
e.display ();
     }
catch(EOFExceptionee)
     {
System.out.println ("End of file Reached...");
     }
finally
{ ois.close ();
fis.close ();
     }
 }
}
   Output:




   File Class: File class of java.io package provides some methods to know the properties of a
   file or a directory. We can create the File class object by passing the filename or directory
   name to it.
          File obj = new File (filename);
          File obj = new File (directoryname);
          File obj = new File ("path", filename);
          File obj = new File ("path", directoryname);
File class Methods:




   Program 10: Write a program that uses File class methods.
   //Displaying file properties
   import java.io.*;
   classFileProp
   { public static void main(String args[])
{ Stringfname = args [0];
        File f = new File (fname);
System.out.println ("File name: " + f.getname ());
System.out.println ("Path:"+ f.getPath ());
System.out.println ("Absolute Path:"+ f.getAbsolutePath ());
System.out.println ("Parent:"+ f.getParent ());
System.out.println ("Exists:"+ f.exists ());
if ( f.exists() )
{ System.out.println ("Is writable: "+ f.canWrite ());
System.out.println ("Is readable: "+ f.canRead ());
System.out.println ("Is executable: "+ f.canExecute ());
System.out.println ("Is directory: "+ f.isDirectory ());
System.out.println ("File size in bytes: "+ f.length ());
        }
    }
}
Ouput:

More Related Content

PPTX
Packages in java
PPTX
Package in Java
PPTX
Packages,static,this keyword in java
PPTX
Java program structure
PPTX
Packages
PPT
Packages and interfaces
PPT
Java package
PPTX
Introduction to package in java
Packages in java
Package in Java
Packages,static,this keyword in java
Java program structure
Packages
Packages and interfaces
Java package
Introduction to package in java

What's hot (20)

PPTX
Packages in java
PPT
Java packages
PPTX
Lecture 19
PPTX
Java package
PPTX
Package In Java
PPT
Packages in java
PPTX
Java packages
PPT
java packages
PPT
Packages,interfaces and exceptions
PPT
Packages in java
PPTX
packages in java & c++
PPTX
5.interface and packages
PDF
Java - Interfaces & Packages
PPT
packages and interfaces
PPTX
Java program structure
PPTX
Pi j4.1 packages
PDF
javapackage
PPTX
Introduction to java
PPT
01slide
DOCX
Unit2 java
Packages in java
Java packages
Lecture 19
Java package
Package In Java
Packages in java
Java packages
java packages
Packages,interfaces and exceptions
Packages in java
packages in java & c++
5.interface and packages
Java - Interfaces & Packages
packages and interfaces
Java program structure
Pi j4.1 packages
javapackage
Introduction to java
01slide
Unit2 java
Ad

Viewers also liked (9)

PDF
Java packages
PDF
Packages
PPTX
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
PPTX
Packaes & interfaces
PDF
Debian Packaging tutorial
PDF
Java packages and access specifiers
PDF
Arrays string handling java packages
PPTX
Java packages
PPS
Packages and inbuilt classes of java
Java packages
Packages
chap 8 : The java.lang and java.util Packages (scjp/ocjp)
Packaes & interfaces
Debian Packaging tutorial
Java packages and access specifiers
Arrays string handling java packages
Java packages
Packages and inbuilt classes of java
Ad

Similar to Unit4 java (20)

PPTX
Packages in java
PPTX
java package in java.. in java packages.
PPTX
java package java package in java packages
PPTX
javapackage,try,cthrow,finallytch,-160518085421 (1).pptx
PDF
JAVA 2-studenttrreadexeceptionpackages.pdf
PPT
7.Packages and Interfaces(MB).ppt .
PPTX
Chap1 packages
PDF
Class notes(week 7) on packages
PPTX
packages in java object oriented programming
PPT
packages.ppt
PPT
packages.ppt
PPT
packages in java programming language ppt
PPT
Unit 4 Java
PPTX
Lecture 11.pptx galgotias College of engineering and technology
PPTX
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
PPT
packages unit 5 .ppt
PPTX
Package.pptx
PPT
PACKAGE.PPT12345678912345949745654646455
PPTX
Packages in java
DOCX
Practice Program-9-Packages-Unit 4.docx
Packages in java
java package in java.. in java packages.
java package java package in java packages
javapackage,try,cthrow,finallytch,-160518085421 (1).pptx
JAVA 2-studenttrreadexeceptionpackages.pdf
7.Packages and Interfaces(MB).ppt .
Chap1 packages
Class notes(week 7) on packages
packages in java object oriented programming
packages.ppt
packages.ppt
packages in java programming language ppt
Unit 4 Java
Lecture 11.pptx galgotias College of engineering and technology
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
packages unit 5 .ppt
Package.pptx
PACKAGE.PPT12345678912345949745654646455
Packages in java
Practice Program-9-Packages-Unit 4.docx

More from mrecedu (20)

PDF
Brochure final
PPT
Unit i
PPT
Filters unit iii
DOCX
Attenuator unit iv
PPT
Two port networks unit ii
PPT
Unit 8
PPT
Unit4 (2)
PPT
Unit5
PPT
Unit4
PPT
Unit5 (2)
PPT
Unit6 jwfiles
PPT
Unit3 jwfiles
PPT
Unit2 jwfiles
PPT
Unit1 jwfiles
PPT
Unit7 jwfiles
PPS
M1 unit vi-jntuworld
PPS
M1 unit v-jntuworld
PPS
M1 unit iv-jntuworld
PPS
M1 unit iii-jntuworld
PPS
M1 unit ii-jntuworld
Brochure final
Unit i
Filters unit iii
Attenuator unit iv
Two port networks unit ii
Unit 8
Unit4 (2)
Unit5
Unit4
Unit5 (2)
Unit6 jwfiles
Unit3 jwfiles
Unit2 jwfiles
Unit1 jwfiles
Unit7 jwfiles
M1 unit vi-jntuworld
M1 unit v-jntuworld
M1 unit iv-jntuworld
M1 unit iii-jntuworld
M1 unit ii-jntuworld

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Empathic Computing: Creating Shared Understanding
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Approach and Philosophy of On baking technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Big Data Technologies - Introduction.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
Per capita expenditure prediction using model stacking based on satellite ima...
Empathic Computing: Creating Shared Understanding
Unlocking AI with Model Context Protocol (MCP)
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Diabetes mellitus diagnosis method based random forest with bat algorithm
Understanding_Digital_Forensics_Presentation.pptx
Approach and Philosophy of On baking technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
MYSQL Presentation for SQL database connectivity
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Review of recent advances in non-invasive hemoglobin estimation
Big Data Technologies - Introduction.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
sap open course for s4hana steps from ECC to s4
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Spectral efficient network and resource selection model in 5G networks
Dropbox Q2 2025 Financial Results & Investor Presentation

Unit4 java

  • 1. UNIT-IV PACKAGES AND INTERFACES DEFINING PACKAGE: This chapter examines two of Java‟s most innovative features: packages and interfaces. Packagesare containers for classes that are used to keep the class name spacecompartmentalized. Packages are stored in a hierarchical manner andare explicitly imported into new class definitions. A package is a container of classes and interfaces. A package represents a directory that contains related group of classes and interfaces. For example, when we write statemens like: import java.io.*; Here we are importing classes of java.io package. Here, java is a directory name and io is another sub directory within it. The „*‟ represents all the classes and interfaces of thatio sub directory. We can create our own packages called user-defined packages or extend the available packages. User-defined packages can also be imported into other classes and used exactly in the same way as the Built-in packages. USE: Packages provide reusability. ADVANTAGES OF PACKAGES:  Packages are useful to arrange related classes and interfaces into a group. This makes all the classes and interfaces performing the same task to put together in the same package.For example , in Java, all the classes and interfaces which perform input and output operations are stored in java.io. package.  Packages hide the classes and interfaces in a separate sub directory, so that accidental deletion of classes and interfaces will not take place.  The classes and interfaces of a package are isolated from the classes and interfaces of another package. This means that we can use same names for classes of two different classes. For example, there is a Date class in java.util package and also there is another Date class in java.sql package.  A group of package called a library. The classes and interfaces of a package are likes books in a library and can be reused several times. This reusability nature of packages makes programming easy. Just think, the package in Java are created by JavaSoft people only once, and millions of programmers all over the world are daily by using them in various programs. Different Types of Packages: There are two types of packages in Java. They are:  Built-in packages  User-defined packages
  • 2. Built-in packages: These are the packages which are already available in Java language. These packages provide all most all necessary classes, interfaces and methods for the programmer to perform any task in his programs. Since, Java has an extensie library of packages, a programmer need not think about logic for doing any task. For everything, there is a method available in Java and that method can be used by the programmer without developing the logic on his own. This makes the programming easy. Here,we introduce some of the important packages of Java SE: Java.lang: lang stands for language. This package got primary classes and interfaces essential for developing a basic Java program. It consists of wrapper classes(Integer, Character, Float etc), which are useful to convert primitive data types into objects. There are classes like String, SttringBuffer, StringBuilder classes to handle strings. There is a thread class to create various individual processes. Runtime and System classes are also present in java.lang package which contain methods to execute an application and find the total memory and free memory available in JVM. Java.util: util stands for utility. This package contains useful classes and interfaces like Stack, LinkedList, Hashtable, Vector, Arrays, etc. thses classes are collections. There are also classes for handling Date and Time operations. Java.io: io stands for input and output. This package contains streams. A stream represents flow of data from one place to another place. Streams are useful to store data in the form of files and also to perform input-output related tasks. Java.awt: awt stands for abstract window toolkit. This helps to develop GUI(Graphical user Interfaces) where programs with colorful screens, paintings and images etc., can be developed. It consists of an important sub package, java.awt.event, which is useful to provide action for components like push buttons, radio buttons, menus etc. Javax.swing: this package helps to develop GUI like java.awt. The „x‟ in javax represents that it is an extended package which means it is a package developed from another package by adding new features to it. In fact, javax.swing is an extended package of java.awt. Java.net: net stands for network. Client-Server programming can be done by using this package. Classes related to obtaining authentication for network, creating sockets at client and server to establish communication between them are also available in java.net package. Java.applet: applets are programs which come from a server into a client and get executed on the client machine on a network. Applet class of this package is useful to create and use applets. Java.text: this package has two important classes, DateFormat to format dates and times, and NumberFormat which is useful to format numeric values. Java.sql: sql stands structured query language. This package helps to connect to databases like Oracle or Sybase, retrieve the data from them and use it in a Java program.
  • 5. User-Defined packages: Just like the built in packages shown earlier, the users of the Java language can also create their own packages. They are called user-defined packages. User-defined packages can also be imported into other classes and used exactly in the same way as the Built-in packages. CREATING AND IMPORTING PACKAGES: packagepackagename; //to create a package packagepackagename.subpackagename;//to create a sub package within a package. e.g.: package pack;  The first statement in the program must be package statement while creating a package.  While creating a package except instance variables, declare all the members and the class itself as public then only the public members are available outside the package to other programs. Program 1: Write a program to create a package pack with Addition class. //creating a package package pack; public class Addition { private double d1,d2; public Addition(double a,double b) { d1 = a; d2 = b; } public void sum() { System.out.println ("Sum of two given numbers is : " + (d1+d2) ); }
  • 6. } Compiling the above program: The –d option tells the Java compiler to create a separate directory and place the .class file in that directory (package). The (.) dot after –d indicates that the package should be created in the current directory. So, out package pack with Addition class is ready. Program 2: Write a program to use the Addition class of package pack. //Using the package pack importpack.Addition; class Use { public static void main(String args[]) { Addition ob1 = new Addition(10,20); ob1.sum(); } } Output: Program 3: Write a program to add one more class Subtraction to the same package pack. //Adding one more class to package pack: package pack; public class Subtraction { private double d1,d2; public Subtraction(double a, double b) { d1 = a;
  • 7. d2 = b; } public void difference() { System.out.println ("Sum of two given numbers is : " + (d1 - d2) ); } } Compiling the above program: Program 4: Write a program to access all the classes in the package pack. //To import all the classes and interfaces in a class using import pack.*; import pack.*; class Use { public static void main(String args[]) { Addition ob1 = new Addition(10.5,20.6); ob1.sum(); Subtraction ob2 = new Subtraction(30.2,40.11); ob2.difference(); } } In this case, please be sure that any of the Addition.java and Subtraction.java programs will not exist in the current directory. Delete them from the current directory as they cause confusion for the Java compiler. The compiler looks for byte code in Addition.java and Subtraction.java files and there it gets no byte code and hence it flags some errors.
  • 8. UNDERSTANDING CLASSPATH: If the package pack is available in different directory, in that case the compiler should be given information regarding the package location by mentioning the directory name of the package in the classpath. The CLASSPATH is an environment variable that tells the Java compiler where to look for class files to import. If our package exists in e:sub then we need to set class path as follows: We are setting the classpath to e:sub directory and current directory (.) an%CLASSPATH% means retain the already available classpath as it is. Creating Sub package in a package: We can create sub package in a package in the format: packagepackagename.subpackagename; e.g.: package pack1.pack2; Here, we are creating pack2 subpackage which is created inside pack1 package. To use the classes and interfaces of pack2, we can write import statement as: import pack1.pack2; Program 5: Program to show how to create a subpackage in a package. //Creating a subpackage in a package package pack1.pack2; public class Sample { public void show () { System.out.println ("Hello Java Learners"); }
  • 9. } Compiling the above program: ACCESSING A PACKAGES: Access Specifier: Specifies the scope of the data members, class and methods.  private members of the class are available with in the class only. The scope of private members of the class is “CLASS SCOPE”.  public members of the class are available anywhere . The scope of public members of the class is "GLOBAL SCOPE".  default members of the class are available with in the class, outside the class and in its sub class of same package. It is not available outside the package. So the scope of default members of the class is "PACKAGE SCOPE".  protected members of the class are available with in the class, outside the class and in its sub class of same package and also available to subclasses in different package also. Program 6: Write a program to create class A with different access specifiers. //create a package same package same; public class A { privateint a=1; publicint b = 2; protectedint c = 3;
  • 10. int d = 4; } Compiling the above program: Program 7: Write a program for creating class B in the same package. //class B of same package package same; importsame.A; public class B { public static void main(String args[]) { A obj = new A(); System.out.println(obj.a); System.out.println(obj.b); System.out.println(obj.c); System.out.println(obj.d); } } Compiling the above program: Program 8: Write a program for creating class C of another package.
  • 11. package another; importsame.A; public class C extends A { public static void main(String args[]) { Cobj = new C(); System.out.println(obj.a); System.out.println(obj.b); System.out.println(obj.c); System.out.println(obj.d); } } Compiling the above program: DIFFERENCES BETWEEN CLASSES AND INTERFACES: Classes Interfaces Classes have instances as variables and Interfaces have instances as abstract methods methods with body and final constants variables. Inheritance goes with extends keyword Inheritance goes with implements keywords. The variables can have any acessspecifier. The Variables should be public, static, final Multiple inheritance is not possible It is possible Classes are created by putting the keyword Interfaces are created by putting the keyword class prior to classname. interface prior to interfacename(super class). Classes contain any type of methods. Classes Interfaces contain mustly abstract methods. may or may not provide the abstractions. Interfaces are exhibit the fully abstractions
  • 12. DEFINING AN INTERFACE AND IMPLEMENTING AN INTERFACE : A programmer uses an abstract class when there are some common features shared by all the objects. A programmer writes an interface when all the features have different implementations for different objects. Interfaces are written when the programmer wants to leave the implementation to third party vendors. An interface is a specification of method prototypes. All the methods in an interface are abstract methods.  An interface is a specification of method prototypes.  An interface contains zero or more abstract methods.  All the methods of interface are public, abstract by default.  An interface may contain variables which are by default public static final.  Once an interface is written any third party vendor can implement it.  All the methods of the interface should be implemented in its implementation classes.  If any one of the method is not implemented, then that implementation class should be declared as abstract.  We cannot create an object to an interface.  We can create a reference variable to an interface.  An interface cannot implement another interface.  An interface can extend another interface.  A class can implement multiple interfaces. An interface is defined much like a class. This is the general form of an interface: access interface name { return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname2 = value; // ... return-type method-nameN(parameter-list); type final-varnameN = value; } Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. The general form of a class that includes the implements clause looks like this: classclassname [extends superclass] [implements interface [,interface...]] { // class-body
  • 13. } If a class implements more than one interface, the interfaces are separated with a comma. If a class implements two interfaces that declare the same method, then the same method will be used by clients of either interface. The methods that implement an interface must be declared public. Also, the type signature of the implementing method must match exactly the type signature specified in the interface definition. Partial Implementations If a class includes an interface but does not fully implement the methods defined by that interface, then that class must be declared as abstract. For example: abstract class Incomplete implements Callback { int a, b; void show() { System.out.println(a + " " + b); } // ... } Here, the class Incomplete does not implement callback( ) and must be declared as abstract. Any class that inherits Incomplete must implement callback( ) or be declared abstract itself. Nested Interfaces An interface can be declared a member of a class or another interface. Such an interface is called a member interface or a nested interface. Anested interface can be declared as public, private, or protected. This differs from a top-level interface, which must either be declared as public or use the default access level, as previously described. When a nested interface is used outside of its enclosing scope, it must be qualified by the name of the class or interface of which it is a member. Thus, outside of the class or interface in which a nested interface is declared, its name must be fully qualified. Here is an example that demonstrates a nested interface: // A nested interface example. // This class contains a member interface.
  • 14. class A { // this is a nested interface public interface NestedIF { booleanisNotNegative(int x); } } // B implements the nested interface. class B implements A.NestedIF { publicbooleanisNotNegative(int x) { return x < 0 ? false : true; } } classNestedIFDemo { public static void main(String args[]) { // use a nested interface reference A.NestedIFnif = new B(); if(nif.isNotNegative(10)) System.out.println("10 is not negative"); if(nif.isNotNegative(-12)) System.out.println("this won't be displayed"); } } Notice that A defines a member interface called NestedIFand that it is declared public. Next, B implements the nested interface by specifying implements A.NestedIF Notice that the name is fully qualified by the enclosing class‟ name. Inside the main( )method, an A.NestedIF reference called nif is created, and it is assigned a reference to a B object. Because B implements A.NestedIF, this is legal.
  • 15. Program 1: Write an example program for interface interface Shape { void area (); void volume (); double pi = 3.14; } class Circle implements Shape { double r; Circle (double radius) { r = radius; } public void area () { System.out.println ("Area of a circle is : " + pi*r*r ); } public void volume () { System.out.println ("Volume of a circle is : " + 2*pi*r); } } class Rectangle implements Shape { doublel,b; Rectangle (double length, double breadth) { l = length; b = breadth; } public void area () { System.out.println ("Area of a Rectangle is : " + l*b ); }
  • 16. public void volume () { System.out.println ("Volume of a Rectangle is : " + 2*(l+b)); } } classInterfaceDemo { public static void main (String args[]) { Circle ob1 = new Circle (10.2); ob1.area (); ob1.volume (); Rectangle ob2 = new Rectangle (12.6, 23.55); ob2.area (); ob2.volume (); } } Output: APPLYING INTERFACE: To understand the power of interfaces, let‟s look at a more practical example. In earlierchapters, you developed a class called Stack that implemented a simple fixed-size stack.However, there are many ways to implement a stack. For example, the stack can be of afixed size or it can be “growable.” The stack can also be held in an array, a linked list, abinary tree, and so on. No matter how the stack is implemented, the interface to the stackremains the same. That is, the methods push( ) and pop( ) define the interface to the stackindependently of the details of the implementation. Because the interface to a stack isseparate from its implementation, it is easy to define a stack interface, leaving it to eachimplementation to define the specifics. Let‟s look at two examples. First, here is the interface that defines an integer stack. Put this in a file called IntStack.java.
  • 17. This interface will be used by both stack implementations. // Define an integer stack interface. interfaceIntStack { void push(int item); // store an item int pop(); // retrieve an item } Applications are:  Abstractions  Multiple Inheritance VARIABLES IN INTERFACES: You can use interfaces to import shared constants into multiple classes by simply declaringan interface that contains variables that are initialized to the desired values. When youinclude that interface in a class (that is, when you “implement” the interface), all of thosevariable names will be in scope as constants. (This is similar to using a header file in C/C++to create a large number of #defined constants or const declarations.) If an interface containsno methods, then any class that includes such an interface doesn‟t actually implement anything. It is as if that class were importing the constant fields into the class name space as finalvariables. The next example uses this technique to implement an automated “decision maker”: importjava.util.Random; interfaceSharedConstants { int NO = 0; int YES = 1; int MAYBE = 2; int LATER = 3; int SOON = 4; int NEVER = 5; } class Question implements SharedConstants { Random rand = new Random(); int ask() {
  • 18. intprob = (int) (100 * rand.nextDouble()); if (prob< 30) return NO; // 30% else if (prob< 60) return YES; // 30% else if (prob< 75) return LATER; // 15% else if (prob< 98) return SOON; // 13% else return NEVER; // 2% } } classAskMe implements SharedConstants { static void answer(int result) { switch(result) { case NO: System.out.println("No"); break; case YES: System.out.println("Yes"); break; case MAYBE: System.out.println("Maybe"); break; case LATER: System.out.println("Later");
  • 19. break; case SOON: System.out.println("Soon"); break; case NEVER: System.out.println("Never"); break; } } public static void main(String args[]) { Question q = new Question(); answer(q.ask()); answer(q.ask()); answer(q.ask()); answer(q.ask()); } } Notice that this program makes use of one of Java‟s standard classes: Random. This class provides pseudorandom numbers. It contains several methods that allow you to obtain random numbers in the form required by your program. In this example, the method nextDouble( ) is used. It returns random numbers in the range 0.0 to 1.0. In this sample program, the two classes, Question and AskMe, both implement the SharedConstants interface where NO, YES, MAYBE, SOON, LATER, and NEVER are defined. Inside each class, the code refers to these constants as if each class had defined or inherited them directly. Here is the output of a sample run of this program. Note that the results are different each time it is run. Later Soon No Yes
  • 20. EXTENDING INTERFACES: One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting classes. When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain. Following is an example: // One interface can extend one or more interfaces.. interface A { void meth1(); void meth2(); } // B now includes meth1() and meth2() -- it adds meth3(). interface B extends A { void meth3(); } // This class must implement all of A and B classMyClass implements B { public void meth1() { System.out.println("Implement meth1()."); } public void meth2() { System.out.println("Implement meth2()."); } public void meth3() { System.out.println("Implement meth3()."); } } classIFExtend {
  • 21. public static void main(String arg[]) { MyClassob = new MyClass(); ob.meth1(); ob.meth2(); ob.meth3(); } } As an experiment, you might want to try removing the implementation for meth1( ) in MyClass. This will cause a compile-time error. As stated earlier, any class that implements an interface must implement all methods defined by that interface, including any that are inherited from other interfaces. Although the examples we‟ve included in this book do not make frequent use of packages or interfaces, both of these tools are an important part of the Java programming environment. Virtually all real programs that you write in Java will be contained within packages. A number will probably implement interfaces as well. It is important, therefore, that you be comfortable with their usage. EXPLORING JAVA.IO.*; A Stream represents flow of data from one place to another place. Input Streams reads or accepts data. Output Streams sends or writes data to some other place. All streams are represented as classes in java.io package. The main advantage of using stream concept is to achieve hardware independence. This is because we need not change the stream in our program even though we change the hardware. Streams are of two types in Java: Streams Java programs perform I/O through streams. Astream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. All streams behave in the same manner, even if the actual physical devices to which they are linked differ. Thus, the same I/O classes and methods can be applied to any type of device. This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Likewise, an output stream may refer to the console, a disk file, or a network connection. Streams are a clean way to deal with input/output withouthaving every part of your code understand the difference between a keyboard and a network,for example. Java implements streams within class hierarchies defined in the java.io package.  Byte Streams: Handle data in the form of bits and bytes. Byte streams are used to handle any characters (text), images, audio and video files. For example, to store an image
  • 22. file (.gif or .jpg), we should go for a byte stream. To handle data in the form of 'bytes' the abstract classes: InputStream and OutputStream are used. The important classes of byte streams are:
  • 24.  BufferedReader/BufferedWriter: - Handles characters (text) by buffering them. They provide efficiency.  CharArrayReader/CharArrayWriter: - Handles array of characters.  InputStreamReader/OutputStreamWriter: - They are bridge between byte streams and character streams. Reader reads bytes and then decodes them into 16-bit unicodecharacters. Writer decodes characters into bytes and then writes.  PrintReader/PrintWriter: - Handle printing of characters on the screen. File: A file represents organized collection of data. Data is stored permanently in the file. Once data is stored in the form of a file we can use it in different programs. Program 1: Write a program to read data from the keyboard and write it to a text file using byte stream classes. //Creating a text file using byte stream classes import java.io.*; class Create1 { public static void main(String args[]) throws IOException { //attach keyboard to DataInputStream DataInputStream dis = new DataInputStream (System.in); //attach the file to FileOutputStream FileOutputStreamfout = new FileOutputStream ("myfile");
  • 25. //read data from DataInputStream and write into FileOutputStream charch; System.out.println ("Enter @ at end : " ) ; while( (ch = (char) dis.read() ) != '@' ) fout.write (ch); fout.close (); } } Output: Program 2: Write a program to improve the efficiency of writing data into a file using BufferedOutputStream. //Creating a text file using byte stream classes import java.io.*; class Create2 { public static void main(String args[]) throws IOException { //attach keyboard to DataInputStream DataInputStream dis = new DataInputStream (System.in); //attach file to FileOutputStream, if we use true then it will open in append mode FileOutputStreamfout = new FileOutputStream ("myfile", true); BufferedOutputStream bout = new BufferedOutputStream (fout, 1024); //Buffer size is declared as 1024 otherwise default buffer size of 512 bytes is used. //read data from DataInputStream and write into FileOutputStream charch;
  • 26. System.out.println ("Enter @ at end : " ) ; while ( (ch = (char) dis.read() ) != '@' ) bout.write (ch); bout.close (); fout.close (); } } OUTPUT: Program 3: Write a program to read data from myfile using FileInputStream. //Reading a text file using byte stream classes import java.io.*; class Read1 { public static void main (String args[]) throws IOException { //attach the file to FileInputStream FileInputStream fin = new FileInputStream ("myfile"); //read data from FileInputStream and display it on the monitor intch; while ( (ch = fin.read() ) != -1 ) System.out.print ((char) ch); fin.close ();
  • 27. } } Output: Program 4: Write a program to improve the efficiency while reading data from a file using BufferedInputStream. //Reading a text file using byte stream classes import java.io.*; class Read2 { public static void main(String args[]) throws IOException { //attach the file to FileInputStream FileInputStream fin = new FileInputStream ("myfile"); BufferedInputStream bin = new BufferedInputStream (fin); //read data from FileInputStream and display it on the monitor intch; while ( (ch = bin.read() ) != -1 ) System.out.print( (char) ch); fin.close (); } } Output:
  • 28. Program 5: Write a program to create a text file using character or text stream classes. //Creating a text file using character (text) stream classes import java.io.*; class Create3 { public static void main(String args[]) throws IOException { Stringstr = "This is an Institute" + "n You are a student"; // take a String //Connect a file to FileWriter FileWriterfw = new FileWriter ("textfile"); //read chars from str and send to fw for (inti = 0; i<str.length () ; i++) fw.write (str.charAt (i) ); fw.close (); } } Output: Program 6: Write a program to read a text file using character or text stream classes. //Reading data from file using character (text) stream classes import java.io.*; class Read3
  • 29. { public static void main(String args[]) throws IOException { //attach file to FileReader FileReaderfr = new FileReader ("textfile"); //read data from fr and display intch; while ((ch = fr.read()) != -1) System.out.print ((char) ch); //close the file fr.close (); } } Output: Note: Use BufferedReader and BufferedWriter to improve the efficiency of the above two programs. Serialization of objects:  Serialization is the process of storing object contents into a file. The class whose objects are stored in the file should implement "Serializable' interface of java.io package.  Serializable interface is an empty interface without any members and methods, such an interface is called 'marking interface' or 'tagging interface'.  Marking interface is useful to mark the objects of a class for a special purpose. For example, 'Serializable' interface marks the class objects as 'serializable' so that they can be written into a file. If serializable interface is not implemented by the class, then writing that class objects into a file will lead to NotSerializableException.  static and transient variables cannot be serialized.  De-serialization is the process of reading back the objects from a file. Program 7: Write a program to create Employ class whose objects is to be stored into a file.
  • 30. //Employ information import java.io.*; importjava.util.*; class Employ implements Serializable { privateint id; private String name; private float sal; private Date doj; Employ (inti, String n, float s, Date d) { id = i; name = n; sal = s; doj = d; } void display () { System.out.println (id+ "t" + name + "t" + sal + "t" + doj); } static Employ getData() throws IOException { BufferedReaderbr = new BufferedReader (new InputStreamReader (System.in)); System.out.print ("Enter employ id : "); int id = Integer.parseInt(br.readLine()); System.out.print ("Enter employ name : "); String name = br.readLine (); System.out.print ("Enter employ salary : " ); floatsal = Float.parseFloat(br.readLine ()); Date d = new Date ();
  • 31. Employ e = new Employ (id, name, sal, d); return e; } } Program 8: Write a program to show serialization of objects. //ObjectOutputStream is used to store objects to a file import java.io.*; importjava.util.*; classStoreObj { public static void main (String args[]) throws IOException { BufferedReaderbr = new BufferedReader (new InputStreamReader (System.in)); FileOutputStreamfos = new FileOutputStream ("objfile"); ObjectOutputStreamoos = new ObjectOutputStream( fos ); System.out.print ("Enter how many objects : "); int n = Integer.parseInt(br.readLine () ); for(inti = 0;i<n;i++) { Employ e1 = Employ.getData (); oos.writeObject (e1); } oos.close (); fos.close (); } } Output:
  • 32. Program 9: Write a program showing deserialization of objects. //ObjectInputStream is used to read objects from a file import java.io.*; classObjRead { public static void main(String args[]) throws Exception { FileInputStreamfis = new FileInputStream ("objfile"); ObjectInputStreamois = new ObjectInputStream (fis); try { Employ e; while ( (e = (Employ) ois.readObject() ) != null) e.display (); } catch(EOFExceptionee) { System.out.println ("End of file Reached..."); } finally { ois.close (); fis.close (); } }
  • 33. } Output: File Class: File class of java.io package provides some methods to know the properties of a file or a directory. We can create the File class object by passing the filename or directory name to it.  File obj = new File (filename);  File obj = new File (directoryname);  File obj = new File ("path", filename);  File obj = new File ("path", directoryname); File class Methods: Program 10: Write a program that uses File class methods. //Displaying file properties import java.io.*; classFileProp { public static void main(String args[])
  • 34. { Stringfname = args [0]; File f = new File (fname); System.out.println ("File name: " + f.getname ()); System.out.println ("Path:"+ f.getPath ()); System.out.println ("Absolute Path:"+ f.getAbsolutePath ()); System.out.println ("Parent:"+ f.getParent ()); System.out.println ("Exists:"+ f.exists ()); if ( f.exists() ) { System.out.println ("Is writable: "+ f.canWrite ()); System.out.println ("Is readable: "+ f.canRead ()); System.out.println ("Is executable: "+ f.canExecute ()); System.out.println ("Is directory: "+ f.isDirectory ()); System.out.println ("File size in bytes: "+ f.length ()); } } } Ouput: