0% found this document useful (0 votes)
26 views

Chapter Two: Advanced Java Topics

This document discusses advanced Java topics including packages, interfaces, object serialization, sockets, applets, and Java Web Start. It provides details on using packages to organize classes and control access. Interfaces are introduced as mechanisms for achieving full abstraction that define methods but do not provide implementations. Classes can implement multiple interfaces to achieve multiple inheritance in Java. Variable types are discussed in relation to abstract classes, interfaces, and concrete classes.

Uploaded by

Abeya Taye
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Chapter Two: Advanced Java Topics

This document discusses advanced Java topics including packages, interfaces, object serialization, sockets, applets, and Java Web Start. It provides details on using packages to organize classes and control access. Interfaces are introduced as mechanisms for achieving full abstraction that define methods but do not provide implementations. Classes can implement multiple interfaces to achieve multiple inheritance in Java. Variable types are discussed in relation to abstract classes, interfaces, and concrete classes.

Uploaded by

Abeya Taye
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 75

Chapter Two

Advanced Java Topics

1
Contents

–Packages and Interfaces


–Object Serialization
–Sockets
–Applets and Java Web Start

2
Introduction  to Packages
• A package is a mechanism to group the
similar type of classes, interfaces and sub-
packages and provide access control. 
•  It organizes classes into single unit. 
• In Java already many predefined packages are
available, used while programming.
For example: java.lang, java.io, java.util etc.

3
Advantages of Packages
• Packages provide code reusability, because a
package has group of classes.
• It helps in resolving naming collision when multiple
packages have classes with the same name.
• Package also provides the hiding of class facility.
Thus other programs cannot use the classes from
hidden package.
• Access limitation can be applied with the help of
packages.
• One package can be defined in another package.
4
Types of Packages
• Built-in packages
– Built-in packages are already defined in java API. For
example: java.util, java.io, java,lang, java.awt,
java.applet, java.net etc.
• User defined packages
– The package we create according to our need is called
user defined package.

5
Creating a Package
• We can create our own package by creating our
own classes and interfaces together.
• The package statement should be declared at
the beginning of the program.
Syntax:
• package <packagename>;
class ClassName 
{
……..
……..
}
6
Cont…

Example: Program to create and use a user defined package in Java.


• // Vehicle.java //Bike.java
package vehicles;
package vehicles; public class Bike implements Vehicle 
{
interface Vehicle      public void run() 
{    {
      System.out.println("Bike is running.");
   public void run();    }
   public void speed() 
   public void speed();    {
}       System.out.println("Speed of Bike: 50 Km/h");
   }
   public static void main(String args[]) 
   {
      Bike bike = new Bike();
      bike.run();
      bike.speed();
   }
}

7
The “import” keyword
• The import keyword provides the access to other
package classes and interfaces in current packages. 
• “import” keyword is used to import built-in and user
defined packages in java program.
• There are different 3 ways to access a package from
other packages.
• Using full qualified name
class Demo extends java.util.Scanner 
{
    //statements
}
8
Cont…

• 2 import only single class


import java.util.Scanner;
class Demo 
{
      // statements
}
• 3 import all classes 
import java.util.*;
class Demo 
{
    // statements
} 9
Interface
• Interface is similar to a class, but it contains
only abstract methods.
• Interface is a mechanism to achieve full
abstraction.
• An interface does not contain any
constructor.
• Once an interface has been defined, one or
more class can implement that interface .
10
Cont…

•  A class that implement interface must


implement all the methods declared in the
interface.
• To implement interface
use implements keyword.
• Since java does not support multiple
inheritance in case of class, but by using
interface it can achieve multiple inheritance.
• If class implements more than one interface, the
interface should separate with coma.
11
Cont…
• Syntax
• interface InterfaceName 
{
   public void method1();
   public void method2();
   <type> variableName = value; 
}
Sample of an interface
interface Employee 
{
   static final Id = 101;
   static final String name = “ABC”;
   void show();
   void getSalary(double salary);
} 12
Cont..
• By default the variables declared in an interface
are static and final. They can not be changed by
implementing class.
• An interface, similar to an abstract class, cannot
be instantiated.
• The method which are declared inside an
interface have no bodies.
• Each class that includes an interface should
implements all the methods.
13
Cont…

14
Cont…
• Note: A class can implement more than one
interface. Java can achieve multiple inheritances
by using interface. 
– A real world example:
import java.io.*;   
interface Vehicle {       
    // all are the abstract methods.
    void changeGear(int a);
    void speedUp(int a);
    void applyBrakes(int a);
}
15
class Bicycle implements Vehicle{
      
    int speed;
    int gear;
      
// to decrease speed
     // to change gear
    @Override
    @Override
    public void applyBrakes(int decrement){
    public void changeGear(int newGear){
          
          
        speed = speed - decrement;
        gear = newGear;     }
    }       
           public void printStates() {
    // to increase speed          System.out.println("speed: " + speed
    @Override               + " gear: " + gear);
    public void speedUp(int increment){     }
           }   
        speed = speed + increment;
    }

16
Employee Interface
public interface Employee {

// fields are public static final constants


double STARTING_SALARY = 200000.0;

// methods are automatically public and


// abstract; must be overridden in
// classes that implement the interface
String description();

double getSalary();
}
17
Student Class Revisted
public class Student {
private String name;
private String course;

public Student(String n, String c) {


name = n;
course = c;
}

public String getName() { return name; }

public String getCourse() { return course; }

public String description() {


return "a student majoring in " + course;
}
}
18
Intern Class
class Intern extends Student implements Employee {
private double income;

public Intern(String n, String c) {


super(n, c);
income = STARTING_SALARY;
}

public double getSalary() { return income; }

public String description() {


return "intern majoring in "+ getCourse() +
"with an income of $" + getSalary();
}
}
19
Using Intern Class
public static void main(String[] args) {

Intern irish = new Intern("Conor", "Math");

System.out.println(irish.getName() + " ," +


irish.description());
}

Output:
Conor, intern majoring in Math
with an income of $200000.0
20
Variable Types
• A variable may have the type of an abstract class,
an interface, or a concrete class (a non-abstract
class).

• Because only a concrete class can be instantiated,


an object may only have the type of a concrete
class.

• All of these are valid variable declarations:


Intern a = new Intern("Conor", "Math");
Student b = new Intern("Conor", "Math");
Employee c = new Intern("Conor", "Math");
21
Variable vs Object Types (Again)
Intern a = new Intern("Conor", "Math");
Student b = new Intern("Conor", "Math");
Employee c = new Intern("Conor", "Math");

• These expressions will not compile:


b.getSalary() // Student does not have getSalary
c.getCourse() // Employee does not have getCourse

• But all of these will:


((Employee)b).getSalary()
((Intern)b).getSalary()
((Student)c).getCourse()
((Intern)c).getCourse()
22
Interface Rules
• Interfaces may specify but do not
implement methods.

• A class that implements the interface


must implement all its methods.

• Interfaces cannot be instantiated.

• Interfaces may contain constants.


23
Cont…

24
Object serialization
• Serialization is a process of converting an object
into a sequence of bytes which can be persisted to
a disk or database or can be sent through streams.
• The reverse process of creating object from
sequence of bytes is called deserialization.

25
Cont…
• A class must implement Serializable interface
present in java.io package in order to serialize its
object successfully.
• Serializable is a marker interface that adds
serializable behaviour to the class implementing it.
• Marker Interface is a special interface in Java
without any field and method.
• Marker interface is used to inform compiler that
the class implementing it has some special
behaviour or meaning.
26
Cont…
• Java provides Serializable API encapsulated under java.io
package for serializing and deserializing objects which
include.
– java.io.serializable
– java.io.Externalizable
• Classes ObjectInputStream and ObjectOutputStream are
high-level streams that contain the methods for serializing
and deserializing an object.
• The ObjectOutputStream class contains many write
methods for writing various data types
– public final void writeObject(Object x) throws IOException
– writeObject() method of ObjectOutputStream class serializes an
object and send it to the output stream. 27
Cont…
• Similarly, the ObjectInputStream class contains the method for
deserializing an object
– public final Object readObject() throws IOException,
ClassNotFoundException
• readObject() method of ObjectInputStream class references
object out of stream and deserialize it.
• NOTE: Static members are never serialized because they are
connected to class not object of class.
• transient Keyword: While serializing an object, if we don't
want certain data member of the object to be serialized we
can mention it transient.
• transient keyword will prevent that data member from being
serialized. 28
Sample code for object serialization and de-serialization

import java.io.Serializable; import java.io.*;


public class SerializeDemo {
public class Employee implements
Serializable { public static void main(String[] args) {
Employee e = new Employee();
e.name = "asmerom ysak";
public String name; e.address = "afar,samara";
public static String address; e.SSN = 11122333;
public transient int SSN; e.number = 101;
try {
public int number; FileOutputStream fileOut
public void mailCheck() { = new
FileOutputStream("src/serialization/employee.ser");
System.out.println("Mailing a ObjectOutputStream out = new
check to “ ObjectOutputStream(fileOut);
+ name + " " + address); out.writeObject(e);
System.out.printf("Serialized data is saved in
} employee.ser");
} } catch (IOException i) {
i.printStackTrace();
}
}

} 29
cont…
import java.io.*;
public class deserialization {
public static void main(String[] args) {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("src/serialization/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Employee class not found");
c.printStackTrace();
return;
System.out.println("Deserialized Employee...“+ + e.name+ e.address + e.SSN + e.number);
}}

30
Socket Programming

31
Socket Programming
What is socket
• Socket represents a end point connection between two
processes that permits them to exchange data.
• Socket programming refers to programming at the
application level/layer!
• There are two types of socket:
– TCP Stream socket: reliable two-way connected communication
streams.
– UDP Datagram socket: unreliable connectionless communication
datagram.
• a door between application process and end-to-end
transport protocols (TCP or UDP) 32
Cont…

33
Development of client/application that
communicate using sockets

• developer has control of everything on


application side but has little control of transport
side of socket.
• only control on transport-layer side is
– (1) choice of transport protocol (TCP or UDP)
– (2) control over a few transport-layer parameters
e.g.max buffer and max segment size

34
Cont…

• to decide which transport-layer protocol, i.e. which


type of socket, our application should use, we need
to understand how TCP and UDP differ in terms of:
– reliability
– Timing
• TCP Reliability : - it is guaranteed that the sent packets will
be received in exactly the same order in which they were
sent
• TCP Timing: TCP congestion control mechanism throttles a
sending process when the network is congested
• TCP guarantees that data will eventually arrive at the receiving
process, but there is no limit on how long it may take.
35
Cont…

• TCP is useful when indefinite amount of data need


to be transferred ‘in order’ and reliably
• otherwise, we end up with jumbled files or invalid information
• examples: HTTP, ftp, telnet, …
• UDP is useful when data transfer should not be
slowed down by extra overhead of reliable TCP
connection
– examples: real-time applications
– e.g. consider a clock server that sends the current time to
its client –if the client misses a packet, it doesn't make
sense to resend it because the time will be incorrect
when the client receives it on the second try
36
Socket-programming using TCP
• When a computer is connected to the internet, it gets an
'IP' address. This address uniquely identifies a computer
on the net.
– In order for a process to connect to another, it must
know the IP address of the host machine.
– In addition to the IP address, the process must know
what 'port' the other process is listening on.
• TCP connection: direct virtual pipe between client's
socket and server's connection socket.

37
Cont…
• A server is the process that is constantly running,
listening for socket connections.
• The client process, attempts to make contact with
the server, when needed.

38
General TCP client/server model description

1. Client initiates contact with server.


2. Server must be ready
– Not dormant (running).
– Have a socket that welcomes initial contact from client
process (welcoming socket).
3. Client initiates TCP connection to the server
• Creates client socket (address of server process, port
number).

39
Cont…
4. Three-way handshake
 Client knocks server welcoming socket.
 Server hears the knock and creates new socket to particular
client (connection socket).
 TCP connection exist between client's socket and server's new
socket.
5. Client sends data via its client socket to server via connection
socket and TCP guarantees the delivery of data which means that
TCP provides reliable byte-stream service between client and
service processes.

40
41
Cont…

42
Client-Server Application

1. Client reads line from standard input (inFromUser


stream) …… BufferedReader.
2. Sends to server via socket (outToServer stream) ……
DataOutputStream
3. Server reads line from socket (inFromClient stream) ……
BufferedReader
4. Server converts line to uppercase, sends back to client
(outToClient stream) …… DataOutputStream
5. Client reads, prints modified line from socket
(inFromServer stream) …… BufferedReader

43
44
Cont…

45
46
Cont…

47
Important notes
• Client has Socket type for clientSocket, server has
ServerSocket type for welcomingSocket and
Socket type for connectionSocket.
• clientSocket needs hostname for server and port
number, serverSocket needs only port number.
• BufferedReader stream is used for reading data
at client or server sides,DataInput/OutputStream
is used for sending data between client and
server through network.

48
Socket -programming using UDP
• UDP:
– Connectionless and unreliable service.
– There isn’t an initial handshaking phase.
– Doesn’t have a pipe.
– Transmitted data may be received out of order, or lost.
• UDP Reliability
– there is no guarantee that the sent datagrams will be
received by the receiving socket

49
Cont…
• UDP Timing
– does not include a congestion-control mechanism, so
a sending process can pump data into network at any
rate it pleases (although not all the data may make it
to the receiving socket)

50
Socket Programming with UDP
• No need for a welcoming socket.
• No streams are attached to the sockets.
• The sending hosts creates “packets” by attaching
the IP destination address and port number to
each batch of bytes.
• The receiving process must discover received
packet to obtain the packet’s information bytes.
• Sockets type is DatagramSocket

51
52
Input/output representation…

53
Cont…
• Note: General mechanisms of TCP and UDP
models for socket programming are the same with
some differences that appears according to the
differences between TCP and UDP features.

54
55
56
Important notes
• Client code:
– DatagramSocket clientSocket = new DatagramSocket() line:
Does n't initiate TCP connection, client host doesn't contact
with the server host according to creating the socket.
– DatagramSocket() doesn't take the server hostname or the
port number as arguments.
– InetAddress IPAddress =
InetAddress.getByName("hostname")line: Get the IP address
of the destination host in order to attach it to every sent
packet.
– Sent packets has a type of DatagramPacket.
– Send/receive methods at UDP programming are instead of
Input/Output streams at TCP programming that attached to
sockets. 57
Server code
• There is no new socket is created for new
connection request from client.
• Unlike TCP, at UDP client code is executed before
server code because client doesn't initiate a
connection with server when client code
executed.

58
applets
• Applet is a Java program that can be embedded into a
web page.
• It runs inside the web browser and works at client side.
• Applet is embedded in a HTML page using the APPLET or
OBJECT tag and hosted on a web server.
• Applets are used to make the web site more dynamic
and entertaining.
• Some important points:
– All applets are sub-classes (either directly or
indirectly) of java.applet.Applet class.

59
Cont…
• Applets are not stand-alone programs. Instead, they run
within either a web browser or an applet viewer.
– JDK provides a standard applet viewer tool
called applet viewer.
• In general, execution of an applet does not begin at
main() method.
• Output of an applet window is not performed
by System.out.println(). Rather it is handled with various
AWT methods, such as drawString().
• The newer javax.swing.JApplet is such an extension, so
more functionality is inherited by extending the JApplet
class instead
60
Life cycle of an applet 

• When an applet begins, the following methods are called, in this


sequence.
•  init( )
• start( )
• paint( )
61
Cont…
• When an applet is terminated, the following sequence of method calls
takes place.
– stop( )
– destroy( )

• init( )
 Initialization occurs when the applet is first loaded (or reloaded),
similarly to the main() method in applications.
 This is the first of your methods to be executed
  Typically this method is used to initialize instance fields, create GUI
components, load sound to play, load image to display.
 Applet does not have constructor. Instead, we override the init()
method to initialize the GUI display when the applet is loaded into
the web browser.
 It is only executed once 62
Cont …
• To provide behavior for the initialization of your applet, override
the init() method in your applet class.
String s= " ";
public void init()
{
s=s+ " int ";
}
 start( ) : 
 The start( ) method is called after init( ).
 it can happen many different times during an applet's lifetime
 Note that init( ) is called once i.e. when the first time an applet is
loaded whereas start( ) is called each time an applet’s HTML
document is displayed onscreen.
 Starting can also occur if the applet was previously stopped.
 For example, an applet is stopped if the reader follows a link to a different
page, and it is started again when the reader returns to this page. 63
Cont…
• Paint():
– this method is called by applet container after init() and start() methods.
–  Painting is how an applet actually draws something on the screen, be it
text, a line, a colored background, or an image.
– You override the paint() method if your applet needs to have an actual
appearance on the screen (that is, most of the time). 
– The paint method is where the real work of this applet (what little work
goes on) really occurs.
– The paint( ) method has one parameter of type Graphics.
– This parameter will contain the graphics context, which describes the
graphics environment in which the applet is running.
– This context is used whenever output to the applet is required.
– called back when the applet drawing area must be refreshed, e.g.,
another window partially covers the applet
64
Example

public void paint(Graphics g) {


g.setFont(f);
g.setColor(Color.red);
g.drawString("Hello again!", 5, 40);
}

65
Cont…
• stop( ) : 
– The stop( ) method is called when a web browser
leaves the HTML document containing the applet
• when it goes to another page, for example.
• When stop( ) is called, the applet is probably running.
– You should use stop( ) to suspend threads that don’t
need to run when the applet is not visible.
• You can restart them when start( ) is called if the user
returns to the page.

66
Cont…

• destroy( ) : 
– The destroy( ) method is called when the
environment determines that your applet needs to be
removed completely from memory.
• At this point, you should free up any resources the applet
may be using.
– The stop( ) method is always called before destroy( ).

67
Cont…
• init( )  and destroy() are only called
once are only called once each 
• start( ) and stop() are called whenever
the browser enter and leaves the page
•  

68
Cont…
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class DemoApplet extends Applet implements ActionListener {

Label getComputers = new Label("Number of computers sold");


TextField numComputers = new TextField(3); // width of textfield
Button clickMe = new Button("Calculate");

public void init() {


add(getComputers); public void actionPerformed(ActionEvent e) {
add(numComputers); int computersInput;
add(clickMe); Graphics g2 = getGraphics();
clickMe.addActionListener(this); computersInput = Integer.parseInt(numComputers.getText());
} g2.setColor(Color.red);
g2.drawString("Resize the Applet to clear previous", 10, 150);
g2.drawString("outputs and demonstrate default layout", 10, 175);
public void paint(Graphics g) { g2.fillRect(10, 100, computersInput * 4, 10);
g.setColor(Color.red); }
}
}

69
Cont…
import java.awt.Color;
import java.awt.Graphics; // import Graphics class
public void paint(Graphics g) {
import javax.swing.*; // import swing package
import javax.swing.JApplet;
// draw the results with
import javax.swing.JOptionPane;
Color bgColor = Color.blue;
public class AdditionApplet extends JApplet {
// sum of the values entered by the user
setBackground(bgColor);
g.setColor(bgColor);
double sum;
g.drawRect(15, 10, 270,
public void init() {
20);
String firstNumber, secondNumber;
double number1, number2;
g.drawString("the sum of
// read in first number from user the two numbers are " +
firstNumber = JOptionPane.showInputDialog("Enter first
floating point value"); sum, 25, 25);
secondNumber = JOptionPane.showInputDialog("Enter second
floating point value"); } //end of paint } //end of
number1 = Double.parseDouble(firstNumber);
number2 = Double.parseDouble(secondNumber); AdditionApplet class
sum = number1 + number2;
}
} 70
Cont…

71
Using java enabled web browser 
• To execute an applet in a web browser we have to write a
short HTML text file that contains a tag that loads the applet.
• We can use APPLET or OBJECT tag for this purpose. Using
APPLET, here is the HTML file that executes AdditionApplet :
<html>
<head>
<title>Digital Clock Applet</title>
</head>
<body bgcolor=white>
<h1>The Digital Clock Applet</h1>
<p> <applet code= AdditionApplet.class width=250 height=80> </applet>
</body>
</html> 

72
Cont…
import java.awt.Color; public void stop() {
import java.awt.Font; clockThread = null;
import java.awt.Graphics; }
import java.util.Calendar; public void run() {
import javax.swing.JApplet; while (Thread.currentThread() == clockThread) {
repaint();
public class DigitalClock extends JApplet implements Runnable {
try {
protected Thread clockThread; Thread.currentThread().sleep(1000);
protected Font font; } catch (InterruptedException e) {
protected Color color; }
}
public void init() { }
// TODO start asynchronous download of heavy resources
public void paint(Graphics g) {
clockThread = null;
Calendar calendar = Calendar.getInstance();
font = new Font("Monospaced", Font.BOLD, 48);
color = Color.green; int hour = calendar.get(Calendar.HOUR_OF_DAY);
} int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
// TODO overwrite start(), stop() and destroy() methods g.setFont(font);
public void start() { g.setColor(color);
if (clockThread == null) {
g.drawString(hour + ":" + minute / 10 + minute % 10
clockThread = new Thread(this);
+ ":" + second / 10 + second % 10, 10, 60);
clockThread.start();
} //end of paint } //end of DigitalClock class
}
} }
73
Cont…

74
Cont….

75

You might also like