Tirgul no. 10 - PowerPoint PPT Presentation

About This Presentation
Title:

Tirgul no. 10

Description:

We write methods which take the base class as an argument, ... using second option the compiler smartly imports only classes that are really ... – PowerPoint PPT presentation

Number of Views:21
Avg rating:3.0/5.0
Slides: 32
Provided by: csHu
Category:
Tags: smartly | tirgul

less

Transcript and Presenter's Notes

Title: Tirgul no. 10


1
Tirgul no. 10
  • Topics covered
  • Polymorphism.
  • Abstract Classes
  • The java API

2
Why use polymorphism (overriding)
We write methods which take the base class as an
argument, at compile time, and by overriding we
achieve the correct response at run
time. Polymorphism enables us to write code
which is easily extensible. Major parts of the
programs are written with respect to the
base classes which enables us to add new derived
classes without making changes to the original
code.
3
Example
We want to implement a class which defines a
mechanic who knows how to tune different kinds
of motors. A well known fact is that the first
thing you do when tuning a motor is to turn it
on. However turning on a gas motor is somewhat
different from turning on a jet motor.
4
Example (cont.)
The class hierarchy of motors we have looks like
this
Motor
JetMotor
GasMotor
public class GasMotor extends Motor public
void turnOn() super.turnOn()
//further actions public class JetMotor
extends Motor public void turnOn()
super.turnOn() //further actions
public class Motor public void turnOn()
checkFuel()
5
Example (cont.)
If we write the following code the method tune
will work 1. for all types of existing motors.
2. additional motors that dont exist currently
(as long as they override the turnOn()
method). public class Mechanic public
void tune(Motor m) m.turnOn()

6
Example no. 2 Door class
  • public class Door
  • private boolean isClosed
  • public Door()
  • isClosed true
  • public void open()
  • isClosed false

public void close() isClosed
true public void printStatus()
if(isClosed) System.out.println("closed
") else System.out.println("open") //e
nd of class Door
7
Extending the Door Class EDoor
  • public class EDoor extends Door
  • private boolean isLocked
  • private long code
  • public EDoor(long n)
  • super()
  • isLocked true
  • code n
  • public void unlock(long code)
  • if(this.codecode)
  • isLocked false

//class Edoor continued public void lock()
close() isLocked true public
void open() if(!isLocked)
super.open() //end of class EDoor
8
Using Doors
  • public class DoorTests
  • public static void main(String args)
  • Door array new Door4
  • array0 new Door()
  • array1 new EDoor(1234)
  • array2 new Door()
  • array3 new EDoor(4)
  • for(int i0 iltarray.length i)
  • arrayi.open()
  • arrayi.printStatus()
  • System.out.println()
  • Question Which doors will be opened? Why?

9
Polymorphism and Dynamic Binding
  • We can refer to an object using a general
    reference, instead of the objects class ref.
  • Examples
  • Door d1 new EDoor(123)
  • EDoor d2 new EDoor(444)
  • Door d3 d2 //upcasting.
  • When we view an EDoor using a Door ref. we can
    only call methods defined by the Door class.
  • Dynamic binding all methods in java are virtual.
    This means that when we invoke a method the
    code that will be executed is the one defined by
    the specific object we are pointing to and NOT by
    the ref we are using.

10
Polymorphism and Dynamic Binding
  • Dynamic binding is used when implemeting method
    overriding.
  • Class Door defined an open() method, which class
    EDoor redefined. When we point to an EDoor using
    a Door ref, and call open() the method called
    will be the one defined by EDoor!
  • Example
  • EDoor d1 new EDoor(137)
  • Door d2 d1 //upcasting
  • d2.open() //will call the open method of EDoor
  • //door will not open because it is locked!

11
Opening the Door
  • //example continued
  • //lets try to unlock the door first
  • d2.unlock(137) //compilation error
  • //Door ref does not see the unlock method!
  • //downcast the door ref to an EDoor ref.
  • ((EDoor)d2).unlock(137) //downcasting.
  • d2.open() //now door will be opened!

12
The instanceof operator
  • When we downcast a ref the compiler checks that
    the downcasting is legal I.e. that the class we
    are downcasting to is an extension of the current
    one. If not we will have a compilation error
  • Example
  • Door d new EDoor(123)
  • String str (String)d //error String is not an
    extension of Door.

13
The instanceof operator
  • However even if the downcasting is legal it
    may still be wrong. This will cause an error
    (exception) called ClassCastException which will
    occur at runtime!
  • Example
  • EDoor d1 new EDoor(123)
  • Object obj d1 //legal upcasting!
  • String str (String) obj // no compilation
    error!!!

14
The instanceof operator
  • The instanceof operator allows us to check at
    runtime whether an object is an instance-of a
    specific class
  • Syntax ltrefNamegt instanceof ltClassNamegt
  • This statement returns true or false.
  • It can be used to prevent wrong downcasting!

15
Corridor Class
  • public class Corridor
  • private Door doors
  • public Corridor(Door first)
  • doors new Door1
  • doors0 first
  • public void addDoor(Door d)
  • Door temp new Doordoors.length1
  • System.arraycopy(doors,0,temp,0,doors.length)
  • tempdoors.length d
  • doors temp

16
Corridor Class (cont.)
  • //class corridor cont.
  • public void openAllDoors(long code)
  • for(int i0 iltdoors.length i)
  • if(doorsi instanceof EDoor)
  • ((EDoor)doorsi).unlock(code)
  • doorsi.open()
  • public void printAllDoors()
  • for(int i0 iltdoors.length i)
  • doorsi.printStatus()
  • //end of class Corridor

17
The final keyword
  • The final keyword can be used in 3 different
    contexts
  • final variable defines a constant i.e. a
    variable who once initiated cant be modified.
  • example public static final int SIZE30
  • final method defines a method that cant be
    overriden by extended classes.
  • final class defines a class that cant be
    extended.
  • Examples String class and Math class.

18
Inheritance scenario
Player
HumanPlayer
ComputerPlayer
OptimizedComputerPlayer
We want the following code to work no matter what
type of player is used, that means changing the
type of player will not force us to change the
code while(!gameIsOver())
player1.move() if(!gameIsOver())
player2.move()
19
First version with problem
public class ComputerPlayer extends Player
public ComputerPlayer(NimBoard board)
super(board) public void move()
//does the move System.out.println("Computer
player moves.") public class
OptimizedComputerPlayer extends Player public
OptimizedComputerPlayer(NimBoard board)
super(board) public void move()
//does the move System.out.println("Optimized
player moves.")
public class Player protected NimBoard
board public Player(NimBoard board)
board board public void
move() public class HumanPlayer extends
Player public HumanPlayer(NimBoard board)
super(board) public void move()
//does the move System.out.println("Human
player moves.")
20
Problem with the code
What happens if someone creates an instance of
Player Player doesn't realy implement the
move() method !! Player isn't a class that we
want instantiated , not all it's methods work
as we expect them to. What we want is that
each sub-class implement its own move()
method and we will only be able to use
sub-classes. The solution is a few slides away.
21
Abstract classes methods(letting someone else
do some of the work)
abstract method - A method that is incomplete ,
it doesn't have an
implementation. abstract class - A class that has
abstract method(s), or a class that you
declare as being abstract.
An abstract class is exactly
the same in all aspects as
other classes except in the following
1.You may not instantiate an
object of this type.
2.It may have unimplemented methods (abstract
methods).
The compiler forces you to declare a class as
abstract if it has abstract methods.
22
Abstract class Example
This is the solution to our earlier
problem public abstract class Player
protected NimBoard board public
Player(NimBoard board) board board
public abstract void move()
General Example public
abstract class MyClass private int data
private int method1(String s) //do
something public abstract String
method2() public abstract void method3(int
i)
23
The java API
  • The java SDK (Standard Development Kit) contains
    a large collection of classes that can be freely
    used.
  • This collection is called the Java API
    Application Programming Interface.
  • Classes are organized into software pacakges
    each containing classes for specific tasks.

24
The java API (cont.)
  • Examples of API packages
  • java.util contains utility classes like Vector,
    Stack, StringTokenizer, Date etc.
  • java.io contains classes for input and output
    handling in java FileReader, InputStream,
    OutputStream etc.
  • java.awt contains classes for Graphical User
    Interface in java (GUI) Window, TextField,
    Button etc.
  • java.net contains classes for networking
    Socket, URL, ServerSocket etc.

25
The java API (cont.)
  • classes have been implemented by Sun and other
    companies (symantec ) .
  • Java is an open source language anyone can read
    the code, and can write extensions. Good
    extensions are incorporated into the standard API
    by Sun.
  • The use of the API is free of charge.

26
API documentation
  • All of the API is thoroughly documented using
    javadoc.
  • Using OOP concepts one only needs to know the
    class interface for using it, without having to
    bother about the implementation details.
  • In cases where the implementation details are
    important for efficiency (or any other reason)
    they are ususally supplied in the API, or in very
    well written books by Sun.
  • A Standard programmer usually uses many API
    classes instead of implementing them by himself.

27
Using the java API
  • Lets take a look at the API documentation
  • The documentation can be downloaded from sun,
    and is also on the net in many places (mirror
    sites)
  • For example
  • http//www.docs.cs.huji.ac.il/java

28
Using the java API
  • Using classes from the api requires specifically
    stating that the current class will use some
    package
  • For example a class that plans to use a
    StringTokenizer will contain one of the 2
    following lines (top of the file before class
    definition)
  • import java.util.StringTokenizer
  • or
  • import java.util.
  • When using second option the compiler smartly
    imports only classes that are really used in the
    current class definition.

29
Using the java API
  • The basic package java.lang is automatically
    imported into any class we write.
  • It contains commonly used classes such as
  • String
  • System
  • Math
  • Wrapper Classes (next tirgul).

30
Using the API WordCollection
  • import java.util.
  • public class WordCollection
  • private Vector words
  • public WordsCollection()
  • words new Vector()
  • public WordsCollection(String data)
  • words new Vector(data.length)
  • for(int i0 i lt data.length i)
  • words.add(datai)
  • //continued on next slide

31
WordCollection (cont.)
  • public void addWord(String word)
  • if(!words.contains(word))
  • words.add(word)
  • public boolean contains(String word)
  • return(words.cotains(word))
  • public String toString()
  • return(words.toString())
  • //end of class WordCollection
Write a Comment
User Comments (0)
About PowerShow.com