Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Tirgul no. 10 Topics covered: Polymorphism. Abstract Classes The java API 1 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. 2 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. 3 Example (cont.) The class hierarchy of motors we have looks like this: Motor JetMotor public class Motor { public void turnOn() { checkFuel(); } } 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 } } 4 Example (cont.) If we write the following code the method tune will work: 1. for all types of existing motors. 2. additional motors that don’t exist currently (as long as they override the turnOn() method). public class Mechanic { public void tune(Motor m) { m.turnOn(); : } } 5 Example no. 2 – Door class public class Door { public void close() { private boolean isClosed; isClosed= true; } public Door() { public void printStatus() { isClosed= true; } public void open() { isClosed= false; if(isClosed) System.out.println("closed"); else System.out.println("open"); } }//end of class Door } 6 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; } close(); isLocked= true; } public void open() { public void unlock(long code) { if(this.code==code) isLocked= false; } //class Edoor continued public void lock() { if(!isLocked) super.open(); } }//end of class EDoor 7 Using Doors: public class DoorTests { public static void main(String[] args) { Door[] array= new Door[4]; array[0]= new Door(); array[1]= new EDoor(1234); array[2]= new Door(); array[3]= new EDoor(4); for(int i=0; i<array.length; i++) { array[i].open(); array[i].printStatus(); System.out.println(); } } Question: Which doors will be opened? Why? 8 Polymorphism and Dynamic Binding We can refer to an object using a general reference, instead of the object’s 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. 9 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! 10 Opening the Door //example continued: //let’s try to unlock the door first: d2.unlock(137); //compilation error: //Door ref doe’s 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! 11 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. 12 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!!! 13 The instanceof operator The instanceof operator allows us to check at runtime whether an object is an instance-of a specific class: Syntax: <refName> instanceof <ClassName> This statement returns true or false. It can be used to prevent wrong downcasting! 14 Corridor Class public class Corridor { private Door[] doors; public Corridor(Door first) { doors= new Door[1]; doors[0]= first; } public void addDoor(Door d) { Door[] temp= new Door[doors.length+1]; System.arraycopy(doors,0,temp,0,doors.length); temp[doors.length]= d; doors= temp; } 15 Corridor Class (cont.) //class corridor cont. public void openAllDoors(long code) { for(int i=0; i<doors.length; i++){ if(doors[i] instanceof EDoor) ((EDoor)doors[i]).unlock(code); doors[i].open(); } } public void printAllDoors() { for(int i=0; i<doors.length; i++) doors[i].printStatus(); } }//end of class Corridor 16 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 can’t be modified. example: public static final int SIZE=30; • final method – defines a method that can’t be overriden by extended classes. • final class – defines a class that can’t be extended. Examples: String class and Math class. 17 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(); } 18 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 HumanPlayer extends Player { public HumanPlayer(NimBoard board) { super(board); } public void move() { //does the move System.out.println("Human 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(){} 19 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 it’s own move() method and we will only be able to use sub-classes. The solution is a few slides away. 20 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. 21 Abstract class Example This is the solution to our earlier problem: General Example [public] abstract class MyClass { private int data; public abstract class Player { protected NimBoard board; private int method1(String s) { //do something } public abstract String method2(); public abstract void method3(int i); } public Player(NimBoard board) { board = board; } public abstract void move(); } 22 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. 23 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. 24 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. 25 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. 26 Using the java API Let’s 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 27 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. 28 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). 29 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 i=0; i < data.length; i++) words.add(data[i]); } //continued on next slide… 30 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 31