Java 1.1 - University of Houston

advertisement
Software Development
prietary© 1997
Summary of Chapter 3
•
A class is a collection of data and methods that operate on that data.
•
An object is a particular instance of a class.
•
Object members (fields and methods) are accessed with a dot
between the object name and the member name.
•
Instance (non-static) variables occur in each instance of a class.
•
Class (static) variables are associated with the class. There is one
copy of a class variable regardless of the number of instances of a
class.
•
Instance (non-static) methods of a class are passed an implicit this
argument that identifies the object being operated on.
•
Class (static) methods are not passed a this argument and therefore
do not have a current instance of the class that can be used to
implicitly refer to instance variables or invoke instance methods.
University of Houston-Clear Lake
Software Development
prietary© 1997
Summary - Continued
•
Objects are created with the new keyword, which invokes a class
constructor method with a list of arguments.
•
Objects are not explicitly freed or destroyed in any way. The Java
garbage collector automatically reclaims objects no longer used.
•
If the first line of a constructor method does not invoke another
constructor with a this() call, or a superclass constructor with a
super( ) call,
•
Java automatically inserts a call to the superclass constructor that
takes no arguments. This enforces "constructor chaining."
•
If a class does not define a constructor, Java provides a default
constructor.
•
A class may inherit the non-private methods and variables of another
class by "subclassing"--i.e., by declaring that class in its extends
clause
University of Houston-Clear Lake
Software Development
Summary - Continued
•
java.lang.Object is the default superclass for a class. It is the root of the
Java class hierarchy and has no superclass itself. All Java classes
inherit the methods defined by Object.
•
Method overloading is the practice of defining multiple methods which
have the same name but have different argument lists.
•
Method overriding occurs when a class redefines a method inherited from
its superclass.
•
Dynamic method lookup ensures that the correct method is invoked for an
object, even when the object is an instance of a class that has overridden
the method.
•
static, private, and final methods cannot be overridden and are not
subject to dynamic method lookup. This allows compiler optimizations
such as inlining.
•
From a subclass, you can explicitly invoke an overridden method of a
superclass with the super keyword.
•
You can explicitly refer to a shadowed variable with the super keyword.
prietary© 1997
University of Houston-Clear Lake
Software Development
prietary© 1997
Summary - Concluded
•
Data and methods may be hidden or encapsulated within a class by
specifying the private or protected visibility modifiers. Members
declared public are visible everywhere.
•
Members with no visibility modifiers are visible only within the
package.
•
An abstract method has no method body (i.e., no implementation).
•
An abstract class contains abstract methods. The methods must be
implemented in a subclass before the subclass can be instantiated.
•
An interface is a collection of abstract methods and constants (static
final variables).
•
Declaring an interface creates a new data type.
•
A class implements an interface by declaring the interface in its
implements clause and by providing a method body for each of the
abstract methods in the interface.
University of Houston-Clear Lake
Software Development
Java 1.1 - What’s New?
Inner classes
Java Beans
A framework for defining reusable modular software components.
Internationalization
A variety of new features that make it possible to write programs that run around the globe.
New event model
A new model for handling events in graphical user interfaces that should make it easier to create
those interfaces.
Other new AWT features
The Java 1.1 AWT includes support for printing, cut-and-paste, popup menus, menu shortcuts,
and focus traversal. It has improved support for colors, fonts, cursors, scrolling, image
manipulation, and clipping.
Applets
JAR files allow all of an applet's files to be grouped into a single archive. Digital signatures allow
trusted applets to run with fewer security restrictions. The HTML <APPLET> tag has new
features.
prietary© 1997
University of Houston-Clear Lake
Software Development
Java 1.1 - More of What’s New?
Object serialization
Objects can now be easily "serialized" and sent over the network or written to disk for
persistent storage.
Security
Java 1.1 includes a new package that supports digital signatures, message digests, key
management, and access control lists.
Java Database Connectivity (JDBC)
A new package that allows Java programs to send SQL queries to database servers. It includes
a "bridge" that allows it to inter-operate with existing ODBC database servers.
Remote Method Invocation (RMI)
An interface that supports distributed Java applications in which a program running on one
computer can invoke methods of Java objects that exist on a different computer.
prietary© 1997
University of Houston-Clear Lake
Software Development
23 Packages in the Core Java API
• java.applet
• java.awt, java.awt.datatransfer, java.awt.event,
java.awt.image, java.awt.peer
• java.beans, java.reflect
• java.io, java.lang, java.math, java.net
• java.rmi, java.rmi.dgc, java.rmi.registry, java.rmi.server
• java.security, java.security.acl, java.security.interfaces
• java.sql, java.text, java.util, java.util.zip
prietary© 1997
University of Houston-Clear Lake
Software Development
prietary© 1997
“Deprecated” Features
• Compile using the -deprecation flag, and
javac provides a detailed warning about each
use of a deprecated feature
• For example, the old AWT event-handling
model has been deprecated in Java 1.1
University of Houston-Clear Lake
Software Development
prietary© 1997
Input to a Java Program
• When a file is opened in Java, an object is
created with an associated stream
• Three stream objects are created for you
when your Java program begins executing
– System.in - the object representing the standard or
default input stream
– System.out - the standard output stream
– System.err - the standard error output stream
• Normally input from the keyboard is read with
System.in.read();
// read a character
University of Houston-Clear Lake
Software Development
prietary© 1997
Example of Reading
import java.io.IOException;
class InputDemo {
public static void main(String args[ ]) {
try {
// Input a single character
System.out.println("Type a character:");
char ch = (char)System.in.read( );
System.out.println("You entered: " + ch);
ch = (char)System.in.read( ); // Ignore new line
// Input a string
System.out.println("Type a string:");
StringBuffer s = new StringBuffer( );
while ((ch = (char)System.in.read( )) != '\n')
s.append(ch);
System.out.println("You entered: " + s);
} catch (IOException e) {
System.out.println("Input error detected");
}
}
}
University of Houston-Clear Lake
Software Development
prietary© 1997
Reading Characters
• System.in.read();
// read a character
• Characters can be stored in most integer data
types because they are represented as 2-byte
integers
• We can treat a character as either an integer
or a character depending upon its use
• To skip a character, you may use read() or
you may use System.in.skip(2)
Since 2 bytes need to be read in
University of Houston-Clear Lake
Software Development
prietary© 1997
Reading Other Types
• System.in.readBoolean();
• System.in.readByte();
• System.in.readChar();
• System.in.readShort();
• System.in.readInt();
• System.in.readLong();
• System.in.readFloat();
• System.in.readDouble();
University of Houston-Clear Lake
Software Development
prietary© 1997
Reading Still Other Types
• System.in.readUnsignedByte();
• System.in.readUnsignedShort();
• System.in.readUTF();
// Unicode formatted strings
• System.in.readFully();
// byte arrays
University of Houston-Clear Lake
Software Development
prietary© 1997
File Streams
Program
Keyboard
Display
Standard
Output
Stream
Standard
Input
Stream
Program
Input File
File
Input
Stream
File
Output
Stream
Output File
University of Houston-Clear Lake
Software Development
Opening a File
FileInputStream inFile = new FileInputStream(“in.dat”);
Sufficient to read a byte stream
StreamTokenizer tokns = new StreamTokenizer(inFile);
Allows the reading of tokens from the stream
tokns.nextToken();
prietary© 1997
int y = (int) tokns.nval;
To get next token from the stream
University of Houston-Clear Lake
Software Development
Getting Several Tokens
import java.io.*;
public class Demo {
public static void main( String argv[ ]) {
Creates a a tokenizer
from a file input stream
FileInputStream inFile = new FileInputStream(“in.dat”);
StreamTokenizer tokns = new StreamTokenizer(inFile);
while (tokns.nextToken() != tokns.TT_EOF) {
tokns.nextToken();
int x = (int) tokns.nval;
tokns.nextToken();
float y = (float) tokns.nval;
System.out.println(“x is “ + x + ” and y is “ + y);
}
inFile.close( );
}
prietary© 1997
University of Houston-Clear Lake
Software Development
prietary© 1997
Labels, Breaks, and Continue
class LabelExample {
public static void main(String args[ ]) {
int i, j;
Outer:
for ( i = 1; i < 100; i++) {
System.out.println("\nOuter loop - " + i);
Inner:
for ( j = 1; j < 10; j++) {
if ( j % 2 == 0)
continue Inner; // Skip even j values
if ( i > 4)
break Outer; // Abort if i > 4
System.out.println( "j = " + j);
} // end of inner for statement
} // end of outer for statement
System.out.println("Program exiting at OuterLoop:");
}
// end of main( ) method
}
// end of class declaration
University of Houston-Clear Lake
Software Development
prietary© 1997
Static Methods May not Reference Instance Variables
Class Goofy {
static int j; // a class variable
int k;
// an instance variable
public static void main(String args[ ]) {
j = 3;
// Okay
k = 2;
// Oops
- will not compile
}
}
University of Houston-Clear Lake
Software Development
prietary© 1997
Finalizer Example
class AnyClass {
AnyClass( ) {
System.out.println("Inside AnyClass( ) constructor");
}
protected void finalize( ) {
System.out.println("Inside AnyClass( ) destructor");
}
}
class FinalDemo {
public static void f( ) {
System.out.println( "Start method f( )");
AnyClass obj1 = new AnyClass( );
System.out.println( "End method f( )");
}
public static void main( String args[ ]) {
System.out.println("Start method main( )");
f( );
AnyClass obj2 = new AnyClass( );
System.out.println( "End method main( )");
}
}
University of Houston-Clear Lake
Software Development
prietary© 1997
Executing the Example
% javac FinalDemo.java
% java FinalDemo
Start method main( )
Start method f( )
Inside AnyClass( ) constructor
End method f( )
Inside AnyClass( ) constructor
End method main( )
%
Note: No output from the destructor calls! The memory wasn’t needed !
University of Houston-Clear Lake
Software Development
prietary© 1997
Random Numbers
class RandomDemo {
public static void main(String args[ ]) {
int rows, cols;
StringBuffer buffer;
for (rows = 1; rows <= 8; rows++) {
buffer = new StringBuffer(128);
for (cols = 1; cols <= 5; cols++)
buffer.append(Math.random( ) + " \t");
System.out.println(buffer);
}
}
}
University of Houston-Clear Lake
Software Development
Random Number Example
% javac RandomDemo.java
% java RandomDemo
0.5597046030343957
0.3986335999333219
0.9723235473289795
0.8446458031727575
0.14420255849434704
0.7295729952178098
0.8731816972495433
0.7452421811338175
0.9551068643472305
0.9093417066560752
0.10284505559195756
0.6279854103489024
0.6621930541886129
0.7575633720986722
0.5701787823427962
0.683133962286439
0.24551363473655874
0.6880812848530756
0.8252374674665472
0.6908809453115774
prietary© 1997
0.9136086039731032
0.37509439742887096
0.2124747582211577
0.6176222433717465
0.23920684828654926
0.24010347958538214
0.3534473746473401
0.6817179247204315
0.16258756915897998
0.7174399453838853
0.2757958093470114
University
of Houston-Clear Lake
0.42532906445802476
Software Development
prietary© 1997
Example Applet
import java.awt.Graphics;
public class Howdy extends java.applet.Applet {
public void paint(Graphics g) {
g.drawString("Howdy", 100, 40);
}
}
University of Houston-Clear Lake
Software Development
prietary© 1997
Example HTML
<html>
<head>
<title>Howdy Example</title>
</head>
<body>
<hr>
<applet
code=Howdy.class
id=Howdy
width=300
height=200 >
</applet>
<hr>
<a href="Howdy.java">Source Code</a>
</body>
</html>
University of Houston-Clear Lake
Download