What is an interface?

Block1-Unit 3
Using Inheritance
Budd 7 - 8
ENG : Ghada Farouk
1
Objectives
• develop a program that will respond to mouse-related
events;
• use the Vector class collection class for holding objects
and primitive data types;
• describe what an exception is in Java and write simple
exception handlers;
• develop programs using inheritance and interfaces;
• use polymorphism and polymorphic variables in your
programs.
2
Objectives
• give an intuitive description of inheritance and the use of
interfaces;
• describe the methods of the class Object from which all
Java classes inherit;
• describe the concept of substitutability and use it as a
programming mechanism;
• describe the difference between a subtype and a
subclass;
• describe and use the forms of inheritance to which Budd
refers under the headings of specialization , specification
and construction .
3
The Graphics class:
java.lang.Object -> java.awt.Graphics
abstract void drawLine(int x1, int y1, int x2, int y2)
// Draws a line, using the current color, between the points (x1, y1) and
(x2, y2) in this graphics context's coordinate
abstract void drawString(String str, int x, int y)
//Draws the text given by the specified string, using this graphics
context's current font and color
abstract void fillOval(int x, int y, int width, int height)
// Fills an oval bounded by the specified rectangle with the current
color.
abstract void fillRect(int x, int y, int width, int height)
// Fills the specified rectangle.
abstract void setColor(Color c)
// Sets this graphics context's current color to the specified color.
4
Switch statement:
switch (<expression>){
case <value1>: <codeBlock1>;
break;
case <value2>: <codeBlock2>;
break;
default : <codeBlock3>;
}
Example: where c is of type char
switch (c){
case '1': case '3': case '5': case '7': case '9':
System.out.println("c is an odd number");
break;
case '0': case '2': case '4': case '6': case '8':
System.out.println("c is an even number");
break;
case ' ':
System.out.println("c is a space");
break;
default :
System.out.println("c is not a number or a space");
}
5
Swicth statement:
Note the following:
•If there is only one statement in a code block, the block does not need
to be enclosed in braces.
•The default code block corresponds to the else block in an if-else
statement and it can be written in any place not necessarily at the end.
•The code blocks are executed based on the value of a variable or
expression, not on a condition.
•The value of <expression> must be of an integer type, or a type that
can be safely converted to int, such as char.
•The case values must be constant expressions that are of the same
data type as the original expression.
•The break keyword is optional. It is used to end the execution of the
switch statement once a code block executes. If it's not used after
codeBlock1, then codeBlock2 executes right after codeBlock1 finishes
executing.
•If a code block should execute when expression is one of a number of
values, each of the values must be specified like this: case <value>:
6
Wrapper class
Integer class: (Wrapper class)
static Integer valueOf(String s)
// Returns an Integer object holding the value of the specified String.
int intValue()
// Returns the value of this Integer as an int
Integer(int value)
//Constructs a newly allocated Integer object that represents the
specified int value.
A vector class can’t be of int type so we create a wrapper class for the
int type called Integer, now I can create a vector of Integer objects.
7
Wrapper class 2
Public class Square{
private int side;
public Square (int s1) { side = s1; }
public int get_Side () { return side; }
public set_Side (int y) { side = y; }
}
Public class my_Square{
Private Square S;
Public my_Square (int L) {S = new Square (L); }
get_Side () { return S. get_Side (); }
}
My_Square here is a wrapper class that hide the implementation of
Square and reuse the members of that class by its way.
8
What is an interface?
•An interface is a description of behaviour.
•An interface can be used as a type name in an argument declared in a
methods header And the matching parameter must be an instance ( in
main ) of a class that implements the interface.
Interface interface_name { header of the interface functions.}
Void fn_name (interface_name x1){ x1.a_fn_in_interface( ) } feature of
substitutability
•A class that implements an interface must provide method definition for
all the interface methods.
interface interface_name{
//Methods with no bodies
}
Class class_name impelements interface_name{
}9
Class WindowAdapter :
java.awt.event.WindowAdapter
public abstract class WindowAdapter extends Object implements
WindowListener
void windowClosing(WindowEvent e)
//Invoked when the user attempts to close the window from the
window's system menu.
Class Jframe:
Methods inherited from class java.awt.Window
public void addWindowListener(WindowListener l)1;
//Adds the specified window listener to receive window events from
this window.
10
import java.awt.event.*;
public class CloseQuit extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
//in CannonWorld class
public CannonWorld() {
setSize(FrameWidth, FrameHeight);
setTitle("Cannon World");
addWindowListener(new CloseQuit());
//add graphical objects and their listeners
JButton fire = new JButton("fire");
fire.addActionListener(new FireButtonListener());
getContentPane().add("North", fire);
slider.addAdjustmentListener(new JScrollBarListener());
getContentPane().add("East", slider);
11}
BorderLayout:
It is the default layout manager.
BorderLayout arranges a container's
components in areas named North,
South, East, West, and Center. These are
BorderLayout's placement constraints.
•The components in North and South are
given their preferred height and are
stretched across the full width of the
container.
•The components in East and West are
given their preferred width and are
stretched vertically to fill the space
between the North and South areas.
• The component in the Center expands
to fill all remaining space.
• getContentPane().add("North", fire);
12
What is an inner class?
A class within a class
Allowed to access their surrounding environment (data field
and methods).
The inside class can access the outside class member.
Are used frequently in building listener objects for handling
events.
13
JButton class:
javax.swing.JButton
JButton(String text)
//Creates a button with text.
public void addActionListener(ActionListener l);
//Adds an ActionListener to the button.
ActionListener interface:
java.awt.event
Has only one method
void actionPerformed(ActionEvent e)
//Invoked when an action occurs.
Class ActionEvent: java.awt.event.ActionEvent
14
Class Jframe: javax.swing.JFrame
Container getContentPane()
// Returns the contentPane object for this frame.
getContentPane().add("North", fire);
Class Container: java.awt.Container
Component add(String name, Component comp)
//Adds the specified component to this container.
getContentPane().add("North", fire);
15
Class JScrollBar :
javax.swing.JScrollBar
JScrollBar(int orientation, int value, int extent, int min, int max)
//Creates a scrollbar with the specified orientation, value, extent, minimum, and
maximum.
//orientation can be given one of the following values:
//JScrollBar.VERTICAL, JScrollBar.HORIZONTAL
int getValue()
// Returns the scrollbar's value.
void addAdjustmentListener(AdjustmentListener l)
// Adds an AdjustmentListener
Interface AdjustmentListener: java.awt.event
void adjustmentValueChanged(AdjustmentEvent e)
// Invoked when the value of the adjustable has changed.
Class AdjustmentEvent:
16
java.awt.event.AdjustmentEvent
//in CannonWorld class
private JScrollBar slider = new JScrollBar(JScrollBar.VERTICAL, 45,5,0, 90);
public CannonWorld() {
setSize(FrameWidth, FrameHeight);
setTitle("Cannon World");
addWindowListener(new CloseQuit());
//add graphical objects and their listeners
JButton fire = new JButton("fire");
fire.addActionListener(new FireButtonListener());
getContentPane().add("North", fire);
slider.addAdjustmentListener(new JScrollBarListener());
getContentPane().add("East", slider);
}
// the following is an inner class for CannonWorld class
private class JScrollBarListener implements AdjustmentListener{
public void adjustmentValueChanged(AdjustmentEvent e){
int angle = slider.getValue();
cannon.setAngle(angle);
message = "Angle: " + angle;
repaint();
}
}
17
PinBall Game
18
19
The Vector class: java.util.Vector
Vector class is, like an array, an indexed data structure;
meaning that each element has a position in the collection and
can dynamically grow as new elements are added.
Vector class stores objects not primitives , to store primitive
types use the wrapper classes.
Methods:
Vector()
private Vector balls;
balls = new Vector( );
//constructs a new vector instance.
20
The Vector class: java.util.Vector 2
void addElement (Object obj)
targets.addElement(new Wall(30, 30, 2, 350));
// Adds the specified object to the end of a vector, increasing its
size by one.
void removeElementAt (int index)
//Removes the element at the specified index.
Object elementAt (int)
PinBall aBall = (PinBall) balls.elementAt(i);
// Returns the element at the specified index.
int size ()
for (int i=0; i<balls.size(); i++)
//Returns the number of elements stored in a vector.
21
How to call the constructor of the parent class?
Inside the constructor of the child just write
super(…………….)
With the suitable arguments.
Ex:
Class PinBall extends CannonBall{
public PinBall (Point loc)
{
super (loc, 8, -5+Math.random(),-15);
}
.
dx
.
}
22
Rectangle class:
java.awt.Rectangle
Data fields:
Int x
// The x coordinate of the Rectangle.
Int y
// The y coordinate of the Rectangle.
Methods:
Rectangle(int x, int y, int width, int height)
//Constructs a new Rectangle whose top-left corner is
specified as (x, y) and whose width and height are
specified by the arguments of the same name.
boolean intersects(Rectangle r)
//Determines whether or not this Rectangle and the
specified Rectangle intersect.
Void setLocation(int x, int y)
// Moves this Rectangle to the specified location
23
MouseListener Interface: java.awt.event
public interface MouseListener{
void mouseClicked(MouseEvent e)
//Invoked when the mouse button has been clicked
//(pressed and released) on a component.
void mouseEntered(MouseEvent e)
//Invoked when the mouse enters a component.
void mouseExited(MouseEvent e)
//Invoked when the mouse exits a component.
void mousePressed(MouseEvent e)
//Invoked when a mouse button has been pressed on a
//component.
void mouseReleased(MouseEvent e)
//Invoked when a mouse button has been released on a
//component.
}//the implemented class for MouseListener interface is
24
MouseAdapter class.
Class MouseEvent :
java.awt.event.MouseEvent
int getX()
//Returns the horizontal x position of the event relative to the source
component.
int getY()
//Returns the vertical y position of the event relative to the source
component
Private class MouseKeeper extends MouseAdapter
{
// it is an inner class in the pinBallGame class.
Public void mousePressed (MouseEvent e) {
Int x = e.getX( );
Int y = e.getY( );
If (fireButton.includes ( x, y) )
//fireButton object from PinBallFire class
Balls.addElement(fireButton.fire( x, y) );
}
}
25
Class MouseAdapter:
java.awt.event.MouseAdapter
Often a programmer is interested in only one or two of the
above events and since implementing an interface in jave
insists on providing a definition to all methods, a class
MouseAdapter is introduced which impalements the
interface but it uses empty methods i.e. it does nothing in
response to any mouse event.
•A programmer should write a new class that inherits
MouseAdapter and overrides the needed methods.
•Then an instance of this new class is created and passed
as an argument to the method addMouseListener which is
inherited from class JFrame.
26
//inherited from class java.awt.Component
public void addMouseListener(MouseListener l)
27
//Adds the specified mouse listener to receive mouse events
from this component. If listener l is null, no exception is thrown
and no action is performed.
Example: // last version of the PinBallGame when I can put my own
target
public class PinBallGame extends JFrame {
public PinBallGame() {
………
addMouseListener(new MouseKeeper( ));
.
}
……..
private class MouseKeeper extends MouseAdapter{
public void mouseReleased (MouseEvent e) {
int x = e.getX();
int y = e.getY();
if ((element != null) && (x > 50)) {
element.moveTo(x, y);
targets.addElement (element);
repaint();
}
}
}
……….
}
28
Class Label:
java.awt.Label
Methods:
Label(String text)
//Constructs a new label with the specified string of text, left justified
void setText(String text)
// Sets the text for this label to the specified text
To add a label to the window:
private Label scoreLabel = new Label ("Score = 0");
.
.
public PinBallGame() {
.
.
getContentPane(). add ("North", scoreLabel); // layput manager
.
}
29
Object ‘public static’ in the main clause
Class PinBallGame…..{
…..main ( ){
…. World = new PinBallGame( );
…..}
// end main
…..Public static PinBallGame world;
………………………………………
…..Public void addScore(int v){
score += v;
scoreLabel.setText (“score ” + score );
}
}
// end of PinBallGame class
Class ScorePad ……{…
public void hitBy (pinBall aBall){
PinBallGame.world.addScore(value);}
…..
}
// end of ScorePad class
30
PinBallTarget interface
PinBall Class Diagram
import java.awt.*;
public interface PinBallTarget
{
public boolean intersects(PinBall aBall);
public void moveTo(int x, int y);
public void paint(Graphics g);
public void hitBy(PinBall aBall);
}
31
Hole class:
PinBall Class Diagram
import java.awt.*;
public class Hole extends Ball implements PinBallTarget {
public Hole (int x, int y){
super(new Point(x,y), 12);
setColor(Color.black);
}
public boolean intersects (PinBall aBall){
int dx = aBall.location().x - location().x;
int dy = aBall.location().y - location().y;
int r = 2 * radius();
return(-r < dx) && (dx < r) && (-r < dy) && (dy < r);
}
public void hitBy (PinBall aBall)
{
aBall.moveTo(0, PinBallGame.FrameHeight + 30);
aBall.setMotion(0, 0);
}
}
32
ScorePad class:
//implements PinBallTarget implicitly
import java.awt.*;
public class ScorePad extends Hole{
protected int value;
public ScorePad (int x, int y, int v){
super (x, y);
value = v;
setColor (Color.red);
}
PinBall Class Diagram
public void hitBy(PinBall aBall){
PinBallGame.world.addScore(value);
}
public void paint (Graphics g){
g.setColor(color);
int r = radius();
g.drawOval(location().x-r, location().y-r, 2*r, 2*r);
String s = "" + value;
g.drawString(s, location().x-7, location().y+1);
}
}33
The mouseReleased method checks the location of the release, and if
it is in the playing area and if a target item was previously selected,
then it adds a new target to the game.
private class MouseKeeper extends MouseAdapter{
public void mousePressed(MouseEvent e) {
element = null;
//locate position of mouse cursor when moused clicked
int x = e.getX();
int y = e.getY();
//if mouse clicked within firing region, create new
//ball and thread, and start thread
if (fireButton.includes(x, y))
balls.addElement(fireButton.fire(x, y));
if (x < 40) { //each target occupies a 40x40 pixel box
switch (y / 40) {
case 2: element = new Hole(0, 0); break;
case 3: element = new Peg(0, 0, 100); break;
case 4: element = new Peg(0, 0, 200); break;
34
case 5: element = new ScorePad(0, 0, 100); break;
case 6: element = new ScorePad(0, 0, 200); break;
case 7: element = new Spring(0, 0); break;
case 8: element = new Wall(0, 0, 2, 15); break;
}
}
}
public void mouseReleased (MouseEvent e) {
int x = e.getX();
int y = e.getY();
if ((element != null) && (x > 50)) {
element.moveTo(x, y);
targets.addElement (element);
repaint();
}
}
}
35
Inheritance
Object class:
java.lang.Object
All classes are derived from a single root class, named
Object. The class Object provide minimum functionality
guaranteed to be common to all objects. This include the
following methods:
boolean equals(Object obj)
//Indicates whether some other object is "equal to" this one.
Class getClass()
//Returns the runtime class of an object
String toString()
// Returns a string representation of the object.
36
Inheritance 2
• The mechanism of inheritance should be used when two (or
more) concepts have a structural relationship. Note that with
objects, a structural relationship almost always implies at least
some behavioral relationship.
• The interface mechanism should be used with two (or more)
concepts having a behavioral relationship but no structural
relationship.
• A class that inherits from an existing class that implements an
interface must of necessity also implement the interface.
• Inheritance is always transitive, so that a class can inherit
features from superclasses many levels away. That is, if class
Dog is a subclass of class Mammal, and class Mammal is a
subclass of class Animal, then Dog will inherit attributes both
from Mammal and Animal.
37
Forms of Inheritance
1.
2.
3.
4.
5.
6.
38
Inheritance for specialization.
Inheritance for specification. ’add abstract class and
abstract methods and parent doesn’t implement actual
behavior ’.
Inheritance for construction. ’if there is a similarities as
between Hole and Ball classes ’.
Inheritance for extension. ’the parent remain untouchable’.
Inheritance for limitation. ‘building class inherit from an
existing one and the super class can’t be modified ’.
Inheritance for combination. ‘back door for the multi_
inheritance concept as to extends from one class and
implements another’
Number class:
java.lang.Number (Abstract class)
public abstract class Number{
public byte byteValue()
{ return (byte) intValue();}
//Returns the value of the specified number as a byte.
public abstract double doubleValue()
//Returns the value of the specified number as a double
public abstract float floatValue()
//Returns the value of the specified number as a float.
public abstract int intValue()
Returns the value of the specified number as an int.
.
.
} subclasses of Number must override methods doubleValue, floatValue,
intValue … all the abstract methods before use them.
39
Modifiers and inheritance
• A public feature (data field or method) can be accessed
outside the class definition. A public class can be
accessed outside the package in which it is declared.
• A protected feature can be accessed only within the
class definition in which it appears, within other classes
in the same package, or within the definition of subclass.
• A private feature can be accessed only within the class
definition in which it appears.
40
The benefits of inheritance
1. Software reusability.
2. Increased reliability. ”test the code on different
situation”
3. Code sharing.
4. Consistency of interface. “similar interface and
behavior during the project”
5. Software components.
6. Rapid prototyping. “large systems divided into
small portions so we can understand it”
7. Polymorphism and framework.
8. Information hiding.
41
The costs of inheritance
1.
2.
3.
4.
42
Execution speed.
Program size.
Message-passing overhead.
Program complexity.
Polymorphism
PinBallTarget target = (PinBallTarget ) targets.elementAt(j);
Here PinBallTarget is an interface implemented in many target classes
and the targets in the code above is a Vector of objects from these
target classes.
So we point to these target classes (children) through a single variable
from a type common to these classes (parent = PinBallTarget );
Subclasses can override behavior inherited from parent classes. For
example, the class Platypus overrides the reproduction behavior
inherited from class Mammal, since Platypuses lay eggs.
Substitutability can also occur through the use of interfaces. An ex. Is
the instance of the class FireButtonListener created in the Cannon
Game (ch 6). The class from which this value was defined was
declared as implementing the interface ActionListener. Because it
implements the ActionListener interface, we can use the value as a
parameter to a method.
43
Polymorphism 2
fire.addActionListener (new FireButtonListener ( )) ;
The function addActionListener expect value of type
ActionListener ‘interface’ but through the run time the
application will look for type FireButtonListener ‘the
implemented class’.
44
Exception class: java.lang.exception
45