Chapter 3 Java

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 38

Chapter 2

Interfaces

 In order to work with a class, you need to


understand the public methods
 methods, return types,…
 after you instantiate, what can you do with it?
 The implementation details are irrelevant to
using the class
 you don’t have to know how things are done
inside the class
Interfaces
 A Java interface is a collection of abstract methods
and constants
 An abstract method is a method header without a
method body
 An abstract method can be declared using the
modifier abstract, but because all methods in an
interface are abstract, usually it is left off
 An interface is used to establish a set of methods
that a class will implement
Interfaces
interface is a reserved word
None of the methods in
an interface are given
public interface Doable a definition (body)
{
public void doThis();
public int doThat();
public void doThis2 (float value, char ch);
public boolean doTheOther (int num);
}

A semicolon immediately
follows each method header
Interfaces
 An interface cannot be instantiated
 Methods in an interface have public visibility by
default
 A class formally implements an interface by:
 stating so in the class header
 providing implementations for each abstract method in the
interface

 If a class asserts that it implements an interface, it


must define all methods in the interface
Interfaces
public class CanDo implements Doable
{
public void doThis ()
implements is a
{
reserved word
// whatever
}

public void doThat () Each method listed


{ in Doable is
// whatever given a definition
}

// etc.
}
Interfaces
 A class that implements an interface can
implement other methods as well
 In addition to (or instead of) abstract
methods, an interface can contain
constants
 When a class implements an interface, it
gains access to all its constants
 Packages are containers for classes that are used to keep the
class name space compartmentalized.
 For example, a package allows you to create a class named
List, which you can store in your own package without
concern that it will collide with some other class named List
stored elsewhere.
 Packages are stored in a hierarchical manner and are
explicitly imported into new class definitions.
 Through the use of the interface keyword, Java allows you to
fully abstract the interface from its implementation.
 Using interface, you can specify a set of methods that can be
implemented by one or more classes.
 The interface, itself, does not actually define any
implementation.
 A class can implement more than one interface. By contrast, a
class can only inherit a single superclass (abstract or
otherwise).
Java provides a mechanism for partitioning the class name
space into more manageable chunks. This mechanism is the
package.
The package is both a naming and a visibility control
mechanism.
You can define classes inside a package that are not
accessible by code outside that package.
You can also define class members that are only exposed to
other members of the same package.
Defining a Package
To create a package is quite easy: simply include a package command as the
first statement in a Java source file.
Any classes declared with in that file will be long to the specified package.
The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the default
package, which has no name.
package pkg;
Here, pkg is the name of the package. For example, package MyPackage;
Socket Programming

 What is a socket?
 Using sockets
 Types (Protocols)
 Associated functions
 Styles
What is a socket?

 An interface between application and network


 The application creates a socket
 The socket type dictates the style of
communication
 reliable vs. best effort
 connection-oriented vs. connectionless
 Once configured, the application can
 pass data to the socket for network transmission
 receive data from the socket (transmitted through
the network by some other host)
Two essential types of sockets
 STREAM
Limit on Number of
 a.k.a. TCP
Processes that can
 reliable delivery successfully request “Listen” for
service at a time service
 in-order guaranteed requests
 connection-oriented Service
Request
 bidirectional
2
Service
1 Request Request
Service Serviced
Process
Request

3
Connect
Two essential types of sockets
• DATAGRAM
– a.k.a. UDP

– unreliable delivery; data can be

lost, although this is unusual


– no order guarantees

– no notion of “connection” – app Process


indicates dest. for each packet
– can send or receive

Send to recipient

Indeterminate
path
Process

Receive from Sender


Ports
 Each host has
Port 0
65,536 ports
Port 1
 Some ports are
reserved for specific Port 65535
apps
 20,21: FTP  A socket provides an interface
to send data to/from the
 23: Telnet
network through a port
 80: HTTP
TCP Sockets
Example: SocketThrdServer.java
SERVER:
1. Create a ServerSocket object
ServerSocket servSocket = new ServerSocket(1234);
2. Put the server into a waiting state
Socket link = servSocket.accept();
3. Set up input and output streams
• use thread to serve this client via link
4. Send and receive data
out.println(awaiting data…);
String input = in.readLine();
5. Close the connection
link.close()
TCP Sockets
Example: SocketClient.java
CLIENT:
1. Establish a connection to the server
Socket link =
new Socket(<server>,<port>);
2. Set up input and output streams

3. Send and receive data

4. Close the connection


Applets and Java Web Start
 This chapter introduces applets—Java programs that are typically embedded in
XHTML (Extensible HyperText Markup Language) documents.
 When a Java-enabled web browser loads a web page containing an applet, the
applet downloads into the browser and executes.
 The application in which an applet executes is known as the applet container.
 The applet container loads the applet’s class(es), creates an instance of the
applet and manages its life cycle.
 The Java Development Kit (JDK) includes one called the appletviewer for testing
applets as you develop them and before you embed them in web pages.
Cont…
 Some browsers don’t come with the plug-in by default.
 You can visit java.com to determine whether your browser is ready to execute
Java applets.
 If not, you can click the Free Java Download button to install Java for your
browser.
 We demonstrate applets using both the appletviewer and web browsers, which
execute Java applets via the Java Plug-In.
 Java Web Start and the Java Network Launch Protocol (JNLP) enable you to
package your applets and applications so that they can be installed onto the
user’s desktop.
Sample Applets Provided with the JDK
 Demonstration applets provided with the JDK.
 Each sample applet comes with its source code.

 The demo directory contains several subdirectories.


 The applets directory contains demonstration applets.
 The jfc (Java Foundation Classes) directory contains applets and applications
that demonstrate Java’s powerful graphics and GUI capabilities.
 Change to the applets directory and list its contents to see the directory
names for the demonstration applets.
 Figure 23.1 provides a brief description of each demo applet.
Sample Applets Provided with the JDK (cont.)
 This TicTacToe demonstration applet allows you to play Tic-Tac-Toe against the computer.
 Change directories to subdirectory TicTacToe, where you’ll find the file example1.html that
loads the applet.
 Execute the applet with the command
appletviewer example1.html
 Loads the XHTML document example1.html specified as its command-line argument.

 Can also open the XHTML document in your browser.


 To play again, click the appletviewer’s Applet menu and select the Reload menu item
(Fig. 23.3), or click the applet again when the game is over.
 To terminate the appletviewer, click the appletviewer’s Applet menu and select the Quit menu
item.
Input and System.in
 interactive program: Reads input from the console.
 While the program runs, it asks the user to type input.
 The input typed by the user is stored in variables in the code.

 Can be tricky; users are unpredictable and misbehave.


 But interactive programs have more interesting behavior.

 Scanner: An object that can read input from many sources.


 Communicates with System.in
 Can also read from files (Ch. 6), web sites, databases, ...

27
Scanner syntax
 The Scanner class is found in the java.util package.
import java.util.Scanner;

 Constructing a Scanner object to read console input:


Scanner name = new Scanner(System.in);

Example:
Scanner console = new Scanner(System.in);

28
Scanner methods
Method Description
nextInt() reads an int from the user and returns it
nextDouble() reads a double from the user
nextLine() reads a one-line String from the user
next() reads a one-word String from the user
Avoid when Scanner connected to System.in

 Each method waits until the user presses Enter.


 The value typed by the user is returned.

 prompt: A message telling the user what input to type.

System.out.print("How old are you? "); // prompt


int age = console.nextInt();
System.out.println("You typed " + age);
29
Scanner example
import java.util.Scanner;

public class UserInputExample {


public static void main(String[] args) {
Scanner console = new Scanner(System.in); age 29

System.out.print("How old are you? "); years 36


int age = console.nextInt();

int years = 65 - age;


System.out.println(years + " years until retirement!");
}
}

 29 underlined):
Console (user input
How old are you?
36 years until retirement!

30
Scanner example 2
 The Scanner can read multiple values from one line.
import java.util.Scanner;
public class ScannerMultiply {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);

System.out.print("Please type two numbers: ");


int num1 = console.nextInt();
int num2 = console.nextInt();

int product = num1 * num2;


System.out.println("The product is " + product);
}
} Please type two numbers: 8 6
The product is 48

31
Clicker 1 - Input tokens
 token: A unit of user input, as read by the Scanner.
 Tokens are separated by whitespace (spaces, tabs, new
lines).
 How many tokens appear on the following line of input?
23 John Smith 42.0 "Hello world" $2.50 " 19"

A. 2 B. 6 C. 7 D. 8 E. 9

32
input tokens
 When a token is the wrong type, the
program crashes. (runtime error)
System.out.print("What is your age? ");
int age = console.nextInt();

Output:
What is your age? Timmy
java.util.InputMismatchException
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
...

33
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
// creates an object of Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
// takes input from the keyboard
String name = input.nextLine(); // prints the name
System.out.println("My name is " + name); // closes the scanner
input.close();
}
}
 Output
 Enter your name: Kelvin My name is Kelvin

 In the above example, notice the line


 Scanner input = new Scanner(System.in);

 Here, we have created an object of Scanner named input.

 The System.in parameter is used to take input from the standard input. It works just

like taking inputs from the keyboard.

 We have then used the nextLine() method of the Scanner class to read a line of text

from the user.


 Now that you have some idea about Scanner, let's explore more about it.

You might also like