Академический Документы
Профессиональный Документы
Культура Документы
Introduction
The main feature of OOP is its ability to support the reuse of code:
Using the classes ( directly ) Extending the classes (via inheritance) Extending interfaces
The features in basic form limited to reusing the classes within a program. What if we want to reuse your classes in other programs without physically copying them ? In Java, this is achieved by using packages, a concept similar to class libraries in other languages.
2
2. Choose a directory on your hard drive as the root of your package classes library.
You need a place on your hard drive to store your package classes. I suggest you create a directory such as c:\javaclasses. This folder becomes the root directory for your packages.
3.Create subdirectories within the package root directory for your package name.
For example, for the package named mypackage.util, create a directory named mypackage in the c:\javaclasses. Then, in the mypackage directory, create a directory named util. Thus, the complete path to the directory that contains the classes for the mypackage.util package is c:\javaclasses\mypackage\util.
For example, save the files that belongs to the mypackage.util package in c:\javaclasses\mypackage\util.
5. Add the root directory for your package to the ClassPath environment variable.
Do not disturb any directories already listed in the ClassPath. For example, suppose your ClassPath is already set to this: C:\Program Files\Java\jdk1.5.0_05\lib; Then, you modify it to look like this: C:\Program Files\Java\jdk1.5.0_05\lib;c:\javaclasses
The package statement creates a package with specified name. All classes declared within that file belong to the specified package. For example: package mypackage.util; The package statement must be the first non-comment statement in the file.
8
Ex: package mypackage.util; public class sum { public int sumInt(int a[]) { int sum=0; for(int i=0;i<a.length;i++) { sum=sum+a[i]; } return sum; } }
9
import mypackage.util.*; class pack_demo { public static void main( String arg[]) {
Contd..
In general, a Java source file can contain any (or all) of the following four internal parts:
A single package statement (optional). Any number of import statements (optional). A single public class declaration (required). Any number of classes private to the package (optional).
11
default public
When a class is declared as public, it is accessible by any other code. If a class has default access, then it can only be accessed by other code within the same package.
12
13
Same class . Subclasses in the same package. Non-subclasses in the same package. Subclasses in different packages. Non-subclasses in different packages.
14
Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. default is visible to same class, subclasses and non-subclasses in same package. protected is visible to same class,subclasses, non-subclasses in the same package and subclasses in different packages.
15
To summarize
java.lang.Math.sqrt(x);
18
Understanding CLASSPATH
We should tell the java run-time system where to look for packages that we have created. There are three methods.
First, you can specify a path to package ( root path ) by setting the CLASSPATH environmental variable. Second, by default, the Java run-time system uses the current working directory as its starting point. Thus, if your package is in the current directory, it will be found.
19
Third, you can use the classpath option with javac and java to specify the path to your package classes.
Example,
package mypackage.util; Method-I : Add root dir to classpath envi variable Method-II : Method-III :
>javac -classpath c:\rootdir path to ur java file >java -classpath c:\rootdir;path to ur class classname then execute your program/class from any place. Execute your program/class from the root directory ( current directory)
20
anyplace :\> javac classpath package_rootpath location_of_ur_java_file anyplace :\>java -classpath packagerootpath;ur_class_path
ur_class_name
21
When packages are developed by different organizations, it is possible that multiple packages will have classes with the same name, leading to name clashing.
package pack1; class Teacher class Student package pack2; class Student class Courses
22
We can import and use these packages like: import pack1.*; import pack2.*; Student student1=new Student(); // Generates compilation error
23
In Java, name clashing is resolved by accessing classes with their fully qualified name.
Java provides a large number of classes groped into different packages based on their functionality. The six Java foundation packages are:
java.lang
Contains classes for math functions, Strings, threads, and exception Contains classes such as vectors, date, calendar etc. Classes for I/O Classes for implementing GUI Classes for networking Classes for creating and implementing applets
25
java.util
java.io
java.awt
java.net
java.applet
Interfaces
An interface, is a way of describing what classes should do, without specifying how they should do it. Interfaces are syntactically similar to classes, but their methods are declared without any body. Any number of classes can implement an interface. One class can implement any number of interfaces.
26
Defining an Interface
27
Default indicates, the interface is only available to other members of the package in which it is declared. public indicates, the interface can be used by any other code.
Variables can be declared inside of an interface, They are implicitly public, static and final.
They cannot be changed. They can be directly accessed by using interface name or class name that implements interface.
They must be initialized with a constant value. All methods declared in an interface are implicitly public. Methods can not be declared as static or final.
28
29
Once an interface has been defined, one or more classes can implement that interface. The general form of a class that implements an
interface. access_specifier class classname [extends superclass] [implements interface1 [,interface2...] ]
{ // class-body }
30
If a class implements more than one interface, the interfaces are separated with a comma. The type signature of the implementing method must match exactly the type signature specified in the interface definition. When you implement an interface method, it must be declared as public.
31
Any instance of any class that implements the interface can be referred by an interface variable. When you call a method through an interface variable, the correct version will be called based on the actual instance of the class referred by the variable. This is one of the key features of interfaces.
32
For example, the stack can be of a fixed size or it can be growable. No matter how the stack is implemented, the interface to the stack remains the same. That is, the methods push( ) and pop( ) define the interface to the stack independently of the details of the implementation. It is easier to add or delete the features to an application with interfaces.
33
The following program creates a class called FixedStack that implements a fixed-length version of an integer stack:
class
34
{
if(tos==stck.length-1) System.out.println("Stack is full."); else stck[++tos] = item;
}
public int pop()
{
if(tos==-1) System.out.println("Stack is Underflow."); else return stck[top--];
} }
35
DynStack(int size)
{
stack = new int[size]; tos = -1;
36
public void
{
// if stack is full, allocate a larger stack
if(tos==stack.length-1) {
int temp[] = new int[stack.length * 2]; // double size for(int i=0; i<stack.length; i++) temp[i] = stck[i]; stack = temp; stck[++tos] = item;
} else
stck[++tos] = item;
37
public int
pop()
{
if(tos==-1)
System.out.println("Stack is Underflow.");
else
return stck[top--];
} }
38
The following class uses both the FixedStack and DynStack implementations.
class IFTest {
public static void main(String args[]) { IntStack mystack; // create an interface reference variable DynStack ds = new DynStack(5); FixedStack fs = new FixedStack(8); mystack = ds; // load dynamic stack and push some numbers onto the stack for(int i=0; i<12; i++) mystack.push(i); mystack = fs; // load fixed stack for(int i=0; i<8; i++) mystack.push(i); .. ..
Accessing multiple implementations of an interface through an interface reference variable is the most powerful way that Java achieves run-time polymorphism.
39
Variables in Interfaces
You can use interfaces to share constants among classes by simply declaring an interface that contains variables which are initialized to the desired values. Ex:-
interface SharedConstants { int NO = 0; int YES = 1; int MAYBE = 2; int LATER = 3; int SOON = 4; int NEVER = 5; }
40
One interface can inherit another by use of the keyword extends. The syntax is similar to 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, otherwise that class should be declared as abstract class.
41
Ex:-
interface A { void meth1(); void meth2(); } interface B extends A { void meth3(); } class MyClass 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()."); } } class IFExtend { public static void main(String arg[]) { MyClass ob = new MyClass();
42
Java.util package
An array list is the most basic type of Java collection. Its similar to an array, but avoids many of the most common problems of working with arrays. Specifically:
If you create an array with 100 elements, then fill it up and need to add a 101st element, you re out of luck. The best you can do is create a new array with 101 elements, copy the 100 elements from the old array to the new one, and then put the new data in the 101st element. With an array list, there s never a limit to how many elements you can create. You can keep adding elements as long as you want.
An array list lets you insert elements into the middle of the collection.
With an array, inserting elements is pretty hard to do. Suppose you have an array that can hold 100 elements, but only the first 50 have data. If you need to insert a new element after the 25th item, you must first make a copy of elements 26 through 50 to make room for the new element. With an array list, you just say you want to insert the new element after the 25th item and the array list takes care of shuffling things around.
If you delete an item from an array, the deleted element becomes null but the empty slot that was occupied by the item stays in the array. When you delete an item from an array list, any subsequent items in the array are automatically moved forward one position to fill in the spot that was occupied by the deleted item.
The ArrayList class actually uses an array internally to store the data you add to the array list.
When you add an item to the array list and the underlying array is full, the ArrayList class automatically creates a new array with a larger capacity and copies the existing items to the new array before it adds the new item.
ArrayList()
ArrayList( size ) Creates an array list with the specified initial capacity.
Unlike an array, you don t have to specify a capacity for an array list. However, you can if you want. Here s a statement that creates an array list with an initial capacity of 100: ArrayList al= new ArrayList(100); If you don t specify a capacity for the array list, the initial capacity is set to 10. Providing at least a rough estimate of how many elements each array list can hold when you create it is a good idea. The capacity of an array list is not a fixed limit. The ArrayList class automatically increases the list s capacity whenever necessary.
49
If you re using Java 1.5, you can also specify the type of elements the array list contains. For example, this statement creates an array list that holds String objects:
ArrayList<String> al = new ArrayList<String>();
General form
ArrayList<E> al=new ArrayList<E>() Here E specifies type of objects that the list will hold. For primitive data types we use following names:
toString()
Ex
// Demonstrate ArrayList. import java.util.*; class ArrayListDemo { public static void main(String args[]) { ArrayList<String> al = new ArrayList<String>(); System.out.println("Initial size of al: " + al.size()); al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "A2"); System.out.println("Size of al after additions: " + al.size()); System.out.println("Contents of al: " + al); al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); } }
54
You don t have to do any pointer management It is taken care by the LinkedList class
LinkedList ls = new LinkedList(); If you re using Java 1.5, you can also specify the type of elements the array list contains. For example, this statement creates an array list that holds String objects:
LinkedList<String> al = new LinkedList<String>();
General form
LinkedList<E> al=new LinkedList<E>() Here E specifies type of objects that the list will hold. For primitive data types we use following names:
toString()
The LinkedList class extends AbstractSequentialList and implements the List , Deque, and Queue interfaces.
LinkedList Class is a generic class that has this declaration: class LinkedList<E>
It provides a linked-list data structure. It has the two constructors, shown here: LinkedList( ) LinkedList(Collection c) The first constructor builds an empty linked list. The second constructor builds a linked list that is initialized with the elements of the collection c.
60
Ex
// Demonstrate LinkedList. import java.util.*; class LinkedListDemo { public static void main(String args[]) { LinkedList<String> ll = new LinkedList<String>(); ll.add("F"); ll.add("B"); ll.add("D"); ll.add("E"); ll.add("C"); ll.addLast("Z"); ll.addFirst("A"); ll.add(1, "A2");
61
System.out.println("Original contents of ll: " + ll); // remove elements from the linked list ll.remove("F"); ll.remove(2); System.out.println("Contents of ll after deletion: + ll); // remove first and last elements ll.removeFirst(); ll.removeLast(); System.out.println("ll after deleting first and last: "+ ll); // get and set a value String val = ll.get(2); ll.set(2, val + " Changed"); System.out.println("ll after change: " + ll); } }
62
63
StringTokenizer
The StringTokenizer constructors are shown here: StringTokenizer(String str) StringTokenizer(String str, String delimiters) StringTokenizer(String str, String delimiters, boolean delimAsToken) In the first version, the default delimiters are used. The default set of delimiters consists of the whitespace characters: pace, tab, newline. In the second and third versions, delimiters is a string that specifies the delimiters. In the third version, if delimAsToken is true, then the delimiters are also returned as tokens when the string is parsed.
64
Method
int countTokens( )
Description
Returns number of tokens left to be parsed.
Returns true if one or more tokens remain in the string and returns false if there are none. Returns the next token as an Object.
65
Date
The Date class encapsulates the current date and time. Date supports the following constructors:
Date( ) Date(long millisec)
The first constructor initializes the object with the current date and time. The second constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970.
66
Description
Returns true if the invoking Date object contains a date that is later than the one specified by date. Otherwise, it returns false. Returns true if the invoking Date object contains a date that is earlier than the one specified by date. Otherwise, it returns false. Duplicates the invoking Date object.
int compareTo(Date date) Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date. (Added by Java 2)
67
Contd..
Method
boolean equals(Object date) long getTime( )
Description
Returns true if the invoking Date object contains the same time and date as the one specified by date.Otherwise, it returns false. Returns the number of milliseconds that have elapsed since January 1, 1970. Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970. Converts the invoking Date object into a string and returns the result.
String toString( )
68
Calendar
The abstract Calendar class provides a set of methods that allows you to convert a time in milliseconds to a number of useful components. Ex: year month day hour minute second. Subclasses of Calendar will provide the specific functionality to interpret time information according to their own rules. An example of such a subclass is GregorianCalendar.
69
Calendar defines the following int constants, which are used when you get or set components of the calendar:
FRIDAY SATURDAY HOUR_OF_DAY JANUARY JULY JUNE MARCH MAY MILLISECOND MINUTE WEEK_OF_YEAR YEAR NOVEMBER SECOND SEPTEMBER SUNDAY THURSDAY TUESDAY WEDNESDAY WEEK_OF_MONTH OCTOBER
AM PM HOUR APRIL AUGUST DATE DAY_OF_MONTH DAY_OF_WEEK DAY_OF_WEEK_IN_MONTH DAY_OF_YEAR DECEMBER MONDAY MONTH FEBRUARY
70
Description
Adds val to the time or date component specified by which. To subtract, add a negative value. Which must be one of the fields defined by Calendar, such as Calendar.HOUR. Returns true if the invoking Calendar object contains a date that is later than the one specified by calendarObj.Otherwise, it returns false. Returns true if the invoking Calendar object contains a date that is earlier than the one specified by calendarObj.Otherwise, it returns false. Zeros all time components in the invoking object.
71
Contd..
final void clear(int which) static Calendar getInstance( ) Zeros the time component specified by which in the invoking object. Returns a Calendar object for the default locale and time zone. Sets the date or time component specified by which to the value specified by val in the invoking object. which must be one of the fields defined by Calendar, such as Calendar.HOUR. Sets various date and time components of the invoking object. Sets various date and time components of the invoking object Sets various date and time components of the invoking object
final void set(int year, int month,int dayOfMonth) final void set(int year, int month, int dayOfMonth, int hours, int minutes) final void set(int year, int month, int dayOfMonth, int hours, int minutes, int seconds)
72
GregorianCalendar
GregorianCalendar is a concrete implementation of a Calendar that provides the normal Gregorian calendar with which you are familiar. The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and time. There are also several constructors for GregorianCalendar class. The default, GregorianCalendar( ), initializes the object with the current local date and time.
73
Contd..
GregorianCalendar(int year, int month, int dayOfMonth) GregorianCalendar(int year, int month, int dayOfMonth, int hours,int minutes) GregorianCalendar(int year, int month, int dayOfMonth, int hours,int minutes, int seconds)
GregorianCalendar provides an implementation of all the abstract methods in Calendar. It also provides some additional methods.
74
Ex:// Demonstrate GregorianCalendar import java.util.*; class GregorianCalendarDemo { public static void main(String args[]) { String months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; int year; // Create a Gregorian calendar initialized // with the current local date and time in the GregorianCalendar gcalendar = new GregorianCalendar();
75
Contd..
// Display current time and date information. System.out.print("Date: "); System.out.print(months[gcalendar.get(Calendar.MONTH)]); System.out.print(" " + gcalendar.get(Calendar.DATE) + " "); System.out.println(year = gcalendar.get(Calendar.YEAR)); System.out.print("Time: "); System.out.print(gcalendar.get(Calendar.HOUR) + ":"); System.out.print(gcalendar.get(Calendar.MINUTE) + ":"); System.out.println(gcalendar.get(Calendar.SECOND)); // Test if the current year is a leap year if(gcalendar.isLeapYear(year)) { System.out.println("The current year is a leap year"); } else { System.out.println("The current year is not a leap year"); } } }
76
java.io package.
java.io package. Some basic points about I/O:
A stream is a linear, sequential flow of bytes of input or output data. Streams are written to the file system to create files. Streams can also be transferred over the Internet.
77
The java.io package contains a fairly large number of classes that deal with Java input and output. Most of the classes consist of:
Byte streams that are subclasses of InputStream or OutputStream Character streams that are subclasses of Reader and Writer
The Reader and Writer classes read and write 16-bit Unicode characters. In Unicode, two bytes make a character.
78
There are a number of different questions to consider when dealing java.io package: What is your format: text or binary? Are you dealing with objects or non-objects? What are your sources and sinks for data? Do you need to use filtering? Sources and sinks for data
What is the source of your data? What will be consuming your output data, that is, acting as a sink?
79
Filtering
Buffering is one filtering method. Instead of going back to the operating system for each byte, you can use a buffer to improve the performane.
80
Subclasses of InputStream
Object
InputStream
ByteArray InputStream
File InputStream
Filter InputStream
Piped InputStream
Sequence InputStream
Data InputStream
Buffered InputStream
LineNumber InputStream
Pushback InputStream
81
InputStream
InputStream is an abstract class that defines Java s model of streaming byte input. All of the methods in this class will throw an IOException on error conditions. The following are the methods in InputStream.
82
83
OutputStream
OutputStream is an abstract class that defines Java s model of streaming byte output. All of the methods in this class return a void value.
84
FileInputStream
The FileInputStream class creates an InputStream that you can use to read bytes from a file. Its two most common constructors are shown here: FileInputStream(String filepath) FileInputStream(File fileObj)
85
FileOutputStream
FileOutputStream creates an OutputStream that you can use to write bytes to a file. Its most commonly used constructors are shown here:
FileOutputStream(String filePath) FileOutputStream(File fileObj) FileOutputStream(String filePath, boolean append) FileOutputStream(File fileObj, boolean append)
86
ByteArrayInputStream
ByteArrayInputStream is an implementation of an input stream that uses a byte array as the source. This class has two constructors, each of which requires a byte array to provide the data source:
87
// Demonstrate ByteArrayInputStream. import java.io.*; class ByteArrayInputStreamDemo { public static void main(String args[]) throws IOException { String tmp = "abcdefghijklmnopqrstuvwxyz"; byte b[] = tmp.getBytes(); ByteArrayInputStream input1 = new ByteArrayInputStream(b); ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0,3); } }
The input1 object contains the entire lowercase alphabet, while input2 contains only the first three letters.
A ByteArrayInputStream implements both mark( ) and reset( ). However, if mark( ) has not been called, then reset( ) sets the stream pointer to the start of the stream
88
ByteArrayOutputStream
ByteArrayOutputStream is an implementation of an output stream that uses a byte array as the destination. ByteArrayOutputStream has two constructors, shown here:
ByteArrayOutputStream( ) ByteArrayOutputStream(int numBytes) In the first form, a buffer of 32 bytes is created. In the second, a buffer is created with a size equal to that specified by numBytes. The buffer is held in the protected buf field of ByteArrayOutputStream. The buffer size will be increased automatically, if needed.
89
Filter input streams read data from a preexisting input stream such as a FileInputStream These streams have an opportunity to work with or change the data before it is delivered to the client program. Filter output streams write data to a preexisting output stream such as a FileOutputStream and have an opportunity to work with or change the data before it is written onto the underlying stream.
90
The methods provided in these classes are identical to those in InputStream and OutputStream.
91
BufferedInputStream
Java s BufferedInputStream class allows you to wrap any InputStream into a buffered stream and achieves performance improvement. BufferedInputStream has two constructors:
The first form creates a buffered stream using a default buffer size (2048 bytes). In the second, the size of the buffer is passed in bufSize. Because the buffer is available,skipping, marking, and resetting of the stream becomes possible.
92
When the first call to read() is made, the BufferedInputStream reads in 2048 bytes (the default size of the buffer) and simply returns 1 byte at a time from the buffer for subsequent reads. There are certainly hardware and operating system caches involved as well, but it is always going to be faster to satisfy a read request from a memory location within the program than it is to make a system call to the operating system. It would also be more efficient to read more than one byte at a time from the stream, especially if it is unbuffered, but as we will see in the next section, some data types within a stream are only made up of a few bytes, so the value of BufferedInputStream still exists.
93
94
95
In computing, the carriage return (CR) is one of the control characters in ASCII code or EBCDIC that commands a printer or other sort of display to move the position of the cursor to the first position on the same line. It is mostly used along with line feed, a move to the next line, while carriage return precedes line feed to indicate new line.
96