Packages and Interfaces

skillfulwolverineSoftware and s/w Development

Dec 2, 2013 (3 years and 8 months ago)

59 views


Unit
-
4


Interfaces

An interface is a collect ion of signatures of functions and final variables. Once an interface i s
created a class can implement the inter f ace. Whenever a class implement s the interf ace,
the class should over ride all the methods

of inter f ace.


Example: Interface_Ex1. java

interface common

{

void accept();

void display();

}

class student implements common

{

int sno;

String sname;

int tfee;

public void accept()//overridden function

{

sno=10;

sname="Sateesh";

tfee=1500;

}

public

void display()//overridden function

{

System.out.println("Student Details : "+sno+" "+sname+" "+tfee);

}

}

class customer implements common

{

int cno;

String cname,product;

int qty,rate;

public void accept() // overridden function

{

cno=20;

cname="Raj";

product="Mouse";

qty=2;

rate=150;

}

public void display() // overridden function

{

System.out.println("Customer Details: "+cno+" "+cname+" "+"product"+qty+"

"+rate);

}

}

class Interface_Ex 1

{

public static void main (String args[]) throws Exception

{

char ch;

common r;

System.out.println ("Enter 1: Student 2: Customer
\
n ");

ch = (char) System.in.read();

if(ch=='1') r = new student();

else r = new customer();

r.accept ();

r.display ();

}

}


Multiple implements
: A class can implement any number of interf
aces such class should

over ride all the methods in all the interfaces.

Ex: interface A

{

void f1( );

}

interface B

{

void f2( );

}

class C implements A,B

{

public void f1( )

{

System.out.println ("Hi");

}

public void f2( )

{

System.out.println ("Hello");

}

}

class Interface_MultipleInheritence

{

public static void main(String args[])

{

//A a = new A( ); // Error, the type cannot be instantiated

//B b = new B( ); //Error, the type cannot be instantiated

C c = new C( ); // OK

c.f1 ( );

c.f2 ( );

A a;

a=c;

a
.f1 ();

B b;

b=c;


b.f2();

}

}




Output :

Hi

Hello

Hi

Hello


Extended Interfaces
: An interface can extended another interface using the key word “ ex
tends “ . Whenever a class implement s the last inter f ace the class should over ride all the
methods in

the inter face chain.


interface A

{

void f1( );

}

interface B extends A

{

void f2( );

}

class C implements B

{

public void f1( )

{

System.out.println("Hi");

}

public void f2( )

{

System.out.println("Hello");

}

}

class Interface_extend_Interface

{

public
static void main(String args[])

{

//A a = new A( ); // Error, the type cannot be instantiated

//B b = new B( ); //Error, the type cannot be instantiated

C c = new C( ); // OK

c.f1( );

c.f2( );

A a;

a=c;

a.f1();

B b;

b=c;

b.f2();

}

}


Output:

Hi

Hello

Hi

He
llo


Partial
implements:

Whenever a class implement s an interface, but does not

over ride all the
methods of the interface such class should be specified as abstract .We should create
another class that ex tends the abstract class and should over ride the

leftover methods.


interface A

{

void f1( );

void f2( );

}

abstract class B implements A

{

public void
f1 (

)

{

System.out.println (
"Hi");

}

}

class C extends B

{

public void
f2 (

)

{

System.out.println (
"Hello");

}

}


class Interface_Abstract

{

public static void
main (
String args[])

{

//A a = new A( ); // Error, the type cannot be instantiated

//B b = new B( ); //Error, the type cannot be instantiated

C c = new C( ); // OK

c.f1( );

c.f2( );

A a;

a=c;

a.f1();

B b;

b=c;

b.f2();

}

}






Interface
vs. Abstract Class

Difference between an interface and an abstract class:

Within the confines of Java syntax, an interface is a type that only defines abstract
methods and constant (final) members. In a more general sense, an interface is an abstract
class

that defines no implementation. Neither an interface nor an abstract class can be
directly instantiated. However, an abstract class may define non
-
constant members and non
-
abstract methods.

An abstract class is often used to define the common set of feat
ures required of its
implementing subclasses, including data structures and method implementations. An
interface is used to define only the methods and constants that are to be shared by its

implementers. You may implement an interface using the implements

keyword and extend
an abstract class using the extends keyword. When you implement an interface, you must
provide the code for all of the methods in the interface. When you extend an abstract class,
you inherit all of the implemented methods and only need

to implement those that were left
undefined (abstract).


1. An abstract class can contain abstract as well as non
-
abstract methods. However an

interface contains only the signatures of the functions.

2. A class can extends only one class. However a class
can implement any number of

interfaces.




C
lasspath
:

The class path is an environment variable set in the operating system which
contains a collection of subdirectories where each such directory can contain any number of
class files. Once the class path is se we are able to access the classes in the subdire
ctories from
any location in the system.


D:
\
>SET CLASSPATH=d:
\
sampackD;

F:
\

sampackF;

Verifying the class path: D:
\
>echo %classpath%

To adding a new subdirectory to previous subdirectories.

D: />SET CLASSPATH=%classpath%;

E:
\
>sampackE;

D: />echo %cl
asspath%


The classpath is an environment variable which will be removed once the command prompt is
closed.


P
ackages



A package is a collection of classes that can be imported into other programs. A package works
similar to a library which is a collectio
n of classes. These classes can be imported and used in
other Java programs. To create a package a subdirectory is required. The name of the package
will be the name of the subdirectory. To make a class belonging to a package, the package

name should be sp
ecified as the first statement in the program








We should set the classpath before compiling the packages.java


D:
\
>SET CLASSPATH=%classpath%;d:
\

sampackD; f :
\

sampackF;


package p1;

public class A

{

public void display()

{

System.out.println("Display from A");

}

}

// filename : B.java // placed in d:
\
sampackD
\
p1
\
B.java

package p1;

public class B

{

public void display()

{

System.out.println("Display from B");

}

}

// filename : C.java

// placed in f:
\
sampackF
\
p2
\
C.java

package p2;

public class C

{

public void display()

{

System.out.println("Display from C");

}

}

// filename : D.java

// placed in f:
\
sampackF
\
p2
\
D.java

package p2;

public class D

{

public void display()

{

System.out.println("Display from D");

}

}




//
filename : pack.java

// this class contains the main( ) , this can be placed any where

import p1.A; // import the selected class

import p1.B;

import p2.*; // import all the classes

class pack

{

public static void main(String args[])

{

A a = new A();

B b =
new B();

C c = new C();

D d = new D();

a.display();

b.display();

c.display();

d.display();

}


}

Out put:

Display from A

Display from B

Display from C

Display from D


The following are the list of some predefined packages which will be installed with JDK.


java.lang: This package contains the important classes like system, string, integer , object
etc. , this package will be imported into every java program by default .






java. io: Contains classes f or I /P and O/P.



java.awt: AWT stands f or Abstract Wind
ows Tool kit , contains classes for GUI .



java.
applet:

For applet management .



java.net: For networking.



java sql : Contains classes f or managing data base transact ions.



java.util : Contains classes for mangeing dates, collect ions et c. ,


Object
Class: It i s defined in java.lang package. Whenever we create a class which does
not inherit any other class by default inherit s the object class i .e. object class is the super
class for all the classes. In Java only the Object class will not have a sup
er class. For all the
remaining classes the Object class becomes the super class.


class Object

{


}

class A

{



}




class B extends A B

{


}


Object class is containing the following methods
:

public int hashCode( ) : Returns the unique identification for

each instance of the class.

Ex: student s = new student ( ) ;







boolean equals(object obj ) : Compares the hash codes of both the object s and returns

true if both are equal, otherwise f al se.


Ex: student t = new student ( );

s! = t;





What is a

a stream?

Java programs perform I/O operations through streams.

A stream is a sequence of data that flow from a source to destination. i.e., producing or
consuming the information. A stream is linked to a physical device by the java I/O system. The
physic
al device may be keyboard, memory, disk file, network socket or console.


Input to a java program
: A java program can consume input from a key board, memory, a disk
file. To bring in information, a program opens a stream on an information source (a file,
memory, a socket) and reads the information sequentially, as shown here: Output from a java
program : A java program can produce output on a console, memory, a disk file or a network
socket.


All of the streams
--
readers, writers, input streams, and output
streams
--
are automatically
opened when created. You can close any stream explicitly by calling its close method. Or the
garbage collector can implicitly close it, which occurs when the object is no longer referenced.


There are two kinds of streams:

1. By
te Streams

2. Character Streams.


The java.io package contains a collection of stream classes (Input Stream and Output Stream

classes, Reader and Writer classes) that support these algorithms for reading and writing. To
use these classes, a program needs
to import the java.io package.


Character Streams versus Byte Streams

Prior to JDK 1.1, the input and output classes (mostly found in the java.io package) only
supported 8
-
bit byte streams. The concept of 16
-
bit Unicode character streams was
introduced in
JDK 1.1. While byte streams were supported via the java.io.InputStream and
java.io.OutputStream classes and their subclasses, character streams are implemented by the
java.io.Reader and java.io.Writer classes and their subclasses.


Most of the functionalit
y available for byte streams is also provided for character streams. The
methods for character streams generally accept parameters of data type char parameters;
while byte streams, you guessed it, work with byte data types. The names of the methods in
both

sets of classes are almost identical except for the suffix, that is, character
-
stream classes
end with the suffix Reader or Writer and bytestream classes end with the suffix Input Stream
and Output Stream. For example, to read files using character stream
s, you would use the
java.io.FileReader class; for reading it using byte streams you would use
java.io.FileInputStream. Unless you are working with binary data, such as image and sound
files, you should use readers and writers (character streams) to read a
nd write information for
the following reasons:


They can handle any character in the Unicode character set (while the byte streams are
limited to ISOLatin
-
1 8
-
bit bytes).



They are easier to internationalize because they are not dependent upon a specific
c
haracter encoding.



They use buffering techniques internally and are therefore potentially much more
efficient than by





Bridging the Gap between Byte and Character Streams


To bridge the gap between the byte and character stream classes, JDK 1.1 and JD
K 1.2 provide
the java.io.InputStreamReader and java.io.OutputStreamWriter classes. The only purpose of
these classes is to convert byte data into character
-
based data according to a specified (or the
platform default) encoding. For example, the static dat
a member "in" in the "System" class is
essentially a handle to the Standard Input (stdin) device. If you want to wrap this inside the
java.io.BufferedReader class that works with character
-
streams, you

use InputStreamReader class as follows:


Buffered Read
er in = new Buffered Reader (new InputStreamReader (System. in));


Character Streams
:

Reader and Writer are the abstract parent classes for character
-
stream based classes in the
java.io package. Reader classes are used to read 16
-
bit character streams and
Writer classes
are used to write to 16
-
bit character streams
.


Byte Streams:

To read and write 8
-
bit bytes, programs should use the byte streams, descendants of Input
Stream and Output Stream. Input Stream and Output Stream provide the API and partial
implementation for input streams (streams that read 8
-
bit bytes) and output streams (streams
that write 8
-
bit bytes). These streams are typically used to read and write binary data such as
images and sounds. Two of the byte stream classes, ObjectInputStrea
m and
ObjectOutputStream, are used for object serialization.


File


File: Files and directories are accessed and manipulated through the java.io.File class.


Note: File class does not provide for I/O. Rather it is often used in the arguments for the file
I/O class methods.


Constructor:

File (String pathname) : The file instance can be created with a path name.

File (String parent, String child) : Allows separate specification of the path and the file name.


Methods
:

long length( ) : Returns the length of
the file. It returns 0 if file is not available.

boolean isDirectory( ) : Returns true if the File object refers to a directory. It returns false if it
refers to a regular file or if no file with the given name exists..

boolean isFile( ) : Returns true if
the given path represent s a file otherwise false.

boolean delete( ) : Deletes the file or directory, if it exist s.

boolean exists( ) : Returns true if the file named by the File object already exists. You could use
this method if you wanted to avoid over
writing the contents of an existing file when

you create a new FileWriter.

boolean canRead( ) : Method asks if the file is readable.





FileInputStream
: This class is used for opening a file in the input mode and allows us to read
the contents of the file
.

Constructor
:

FileInputStream (String filename) throws FileNotFoundException: Opens the given file in the
input mode. If this file can’t be opened the FileNotFoundException will be thrown.


Methods:

int read( ) throws IOException : Reads a character from
the file and returns the ASCI I value of
that character . It returns

1 or EOF.

void close( ) throws IOException : Closes the opened file.


FileOutputStream
: Opens a file in the output mode, which al lows us to write the data into the
file.

Constructor:

Fi
leOutputStream (String filename) throws IOException: This constructor creates a
FileOutputStream that sends its output to the file named by the specified String.

FileOutputStream (File fileobject) throws IOException: This constructor creates a
FileOutputSt
ream that sends its output to the file represented by the specified File.


Methods
:

void write( int val ) throw IOException : This method writes a byte containing the low
-
order
eight bits of the given value to the output stream.

Write ( ) : Takes an ASCII
value and writes the given character into the file.

void close( ) throws IOException : This method closes this file output stream and releases any
resources used by it.


Example: FileIP_OPStreams.java

/ / This program takes a file name, opens that file and

displays the contents of file on console.


import java.io.*;

class FileIP_OPStreams

{

public static void main(String args[])

{

try

{

String in_fname = "d://inputfile.txt";

String out_fname = "d://outputfile.txt";

FileInputStream fin = new FileInputStream
(in_fname);

FileOutputStream fout = new FileOutputStream (out_fname);

int ch = fin.read(); // to read 1st character

while (ch !=
-
1) // while(ch != EOF)

{

// displaying on console

System.out.print( (char) ch);

// Wrinting into output file

fout.write(ch);

c
h = fin.read(); // read remaining characters

}

fin.close();

fout.close();

}



catch(FileNotFoundException ex)

{

System.out.println("File not found");

}

catch(IOException ex)

{

System.out.println("Read/Write Error");

}

}

}


File Reader
: File Reader stream i
s used to read character data from text files. It is a subclass of
InputStreamReader that uses a default buffer size (8192 bytes) to read bytes from a file and
the default character encoding scheme to convert the bytes to characters. If you need to
specify

the character encoding or the buffer size, wrap an InputStreamReader around a
FileInputStream.


Constructors:

public FileReader(String fileName) throws FileNotFoundException This constructor creates a
FileReader that gets its input from the file named by
the specified String.

public FileReader(File file) throws FileNotFoundException: This constructor creates a
FileReader that gets its input from the file represented by the specified File.


FileWriter
: FileWriter stream is used to write character data into
text files. It is a subclass of

OutputStreamWriter that uses a default buffer size (8192 bytes) to write bytes to a file and the
default character encoding scheme to convert characters to bytes. If you need to specify the
character encoding or the buffer s
ize, wrap an OutputStreamWriter around a
FileOutputStream.


Constructors:

public FileWriter(String fileName) throws IOException: This constructor creates a FileWriter
that sends its output to the file named by the specified String.

public FileWriter(String

fileName, boolean append) throws IOException : This constructor
creates a FileWriter that sends its output to the named file. If append is true, the stream is
positioned at the end of the file, and data is appended to the end of the file. Otherwise, if
ap
pend is false, the stream is positioned at the beginning of the file, and any previous data is
overwritten.


Example: CopyFile.java

The following Copy File program uses File Reader and FileWriter to copy the contents of a file
named inpufile.txt into a
file called outputfile.txt :

The read( ) method obtains one character at a time from the File. (For the host system this will
correspond to one byte at a time.




import java.io.*;

public class CopyFile

{

public static void main(String[] args) throws IOExc
eption

{

try

{

File inputFile = new File("D://sateesh_inputfile.txt ");

File outputFile = new File("D://sateesh_outputfile.txt ");

FileReader in = new FileReader(inputFile);

FileWriter out = new FileWriter(outputFile);

int c;

while ((c = in.read()) !=
-
1)

out.write(c);

in.close();

out.close();

System.out.println("One file is copied. (D://sateesh_outputfile.txt)");

}

catch(FileNotFoundException ex)

{

System.out.println("File not found");

}

}

}


Buffered Reader
: The Buffered Reader, buffers the characters and

converts them into

the string format.


Constructors:

public BufferedReader(Reader in) : This constructor creates a BufferedReader that buffers
input from the given Reader using a buffer with the default size of 8192 characters.

public BufferedReader(Reade
r in, int sz) : This constructor creates a BufferedReader that
buffers input from the given Reader, using a buffer of the given size.


Methods
:

String readLine( ) throws IOExcept ion : Reads a line (String) from given input stream or null if
the end of the

stream has been reached.

InputStreamReader: The InputStreamReader reads the data from the given input stream in the
byte format and converts into the character format. i .e. , the InputStreamReader converts the
data from the byte streams to character stre
ams.This class is used to bridge the gap between a
Reader, and an InputStream.


Connect a Buffered Reader, to an InputStreamReader which is connected to an InputStream
called 'in'.

BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) )
;

You can do the same with an OutputStream to a Writer (OutputStreamWriter).



Constructors
:

public InputStreamReader(InputStream in) : This constructor creates an InputStreamReader
that gets its data from in and translates bytes to characters using the
system's default
encoding scheme.

/ / To accept a file name as command line argument and to display the content s of file along
with the line no’s.

import java.io.*;

class ReadLineNos

{

public static void main(String args[])

{

try

{

String fname = "D://sat
eesh_inputfile.txt";

FileInputStream fin = new FileInputStream (fname);

InputStreamReader isr = new InputStreamReader (fin);

BufferedReader br = new BufferedReader(isr);

Or

BufferedReader br = new BufferedReader(new InputStreamReader(new
FileInputStream(fn
ame))); //this statement can be used instead of above 3 lines

String str = br.readLine( );

int n = 0;

while( str != null)

{

n++;

System.out.println(n+": "+str);

str = br.readLine();

}

br.close();

}

catch(Exception ex)

{

System.out.println("Error: "+ex);

}

}

}


LineNumberReader
: A buffered character
-
input stream that keeps track of line numbers. A
line is considered to be terminated by any one of a line feed ('
\
n'), a carriage return ('
\
r'), or a
carriage return followed immediately by a linefeed.


Construct
ors
:

LineNumberReader Reader): Create a new line
-
numbering reader, using the default input
-
buffer size.

LineNumberReader (Reader, int): Create a new line
-
numbering reader, reading characters into
a buffer of the given size.


Methods
:

setLineNumber ( ) : Th
is method enable you to set the internal line number count maintained
by LineNumberInputStream.


setLineNumber ( ) : This method enable you to get the internal line number count maintained
by LineNumberInputStream.


readLine( ) : This method is used to rea
d a line of text.

read( ) : This method is used to read single character.

skip( ) : This method is used to skip number of characters.



Example : LineNumberReader_Ex1.java

import java.lang.System;

import java.io.LineNumberReader;

import java.io.FileReader;

import java.io.BufferedWriter;

import java.io.IOException;

public class LineNumberReader_Ex1

{

public static void main(String args[]) throws IOException

{

FileReader inFile = new FileReader("D://sateesh_inputfile.txt");

LineNumberReader inLines = new Line
NumberReader(inFile);

String inputLine;

while ((inputLine=inLines.readLine()) != null)

{

System.out.println(inLines.getLineNumber()+". "+inputLine);



}

}


Output :

1.

2. This file is created

3. for testing io streams.

4.

5. fileinputstreamreader,

6. fileo
utputstreamreader,

7. bufferedreader etc.,