Object Oriented Programming Debapriyo Majumdar Programming and Data

  • Slides: 43
Download presentation
Object Oriented Programming Debapriyo Majumdar Programming and Data Structure Lab M Tech CS I

Object Oriented Programming Debapriyo Majumdar Programming and Data Structure Lab M Tech CS I – Semester I Indian Statistical Institute Kolkata August 7 and 14, 2014

Objects Real world objects, or even people! A person travels by metro. Person Buy

Objects Real world objects, or even people! A person travels by metro. Person Buy ticket Get in Scans the ticket Metro Driver Get out Travels Runs, Stops Scan Machine § Different objects all performing their duties § Objects are related to each other too 2

Objects § State and Behavior § States of the person – Name, Profession, Current

Objects § State and Behavior § States of the person – Name, Profession, Current location, … § States of the metro – AC/Non-AC, Color, Location, Number of coaches, … § Behavior: actions performed by the object – Person: Travel, Attending a class, Eating – Metro: Running, Stopping, … 3

Independence and Dependency Metro Person Behavior that matters to the person Behavior that matters

Independence and Dependency Metro Person Behavior that matters to the person Behavior that matters to the metro Opens the door Buys the ticket Transports Avails all the facilities Closes the door Announces present and next station Provides a system for buying tickets Provides a system for validating tickets § Consider: some changes in the door opening technology § The functionality for the passenger will remain the same – There will be changes in the internal implementation of the doors 4

Exercise – The PDS Lab § Exercise: Consider the scenario of this class –

Exercise – The PDS Lab § Exercise: Consider the scenario of this class – PDS Lab course § Identify the objects, their states and behaviors, what do the objects provide to each other 5

The Java Hello World Program § Create a directory called “isical” inside day. X/java

The Java Hello World Program § Create a directory called “isical” inside day. X/java § Open a file named Main. java inside isical package isical; public class Main { public static void main(String[] args) { System. out. println("Hello World!"); } } 6

Compile and Run! § Your path: XYZ/java/isical/ § Go to the directory XYZ/java §

Compile and Run! § Your path: XYZ/java/isical/ § Go to the directory XYZ/java § Compile: $ javac isical/Main. java § A file called Main. class should be created § Run $ java isical/Main 7

Object oriented programming The instructor to write down the name of all the students

Object oriented programming The instructor to write down the name of all the students Overview: – A list of students is passed to the instructor – Every student can tell their names – Instructor has a method to write down the names 8

The Student Object File: Student. java package isical; public class Student { private String

The Student Object File: Student. java package isical; public class Student { private String name; // The name of the student private int roll. Number; // The numeric roll number of the student } 9

The Student Object File: Student. java package isical; public class Student { private String

The Student Object File: Student. java package isical; public class Student { private String name; // The name of the student private int roll. Number; // The numeric roll number of the student Now compile Student. java /** * Constructs an instance of a student * @return */ public Student(String name, int roll. Number) { this. name = name; this. roll. Number = roll. Number; } } 10

The Student Object File: Student. java package isical; What does the Student class do

The Student Object File: Student. java package isical; What does the Student class do for me? Nothing yet!! public class Student { private String name; The student needs // The name of the student and roll number!! private int roll. Number; // The numeric roll number of the student to tell his/her name /** * Constructs an instance of a student * @return */ public Student(String name, int roll. Number) { this. name = name; this. roll. Number = roll. Number; } } 11

The Student Object File: Student. java package isical; public class Student { ………… ADD

The Student Object File: Student. java package isical; public class Student { ………… ADD THE FOLLOWING LINES ………… /* What can the student do? */ public String get. Name() { return name; // Returns the name } Now (s)he can public int get. Roll. Number() { return roll. Number; } } 12

The Instructor Object Filename: ? package isical; public class Instructor { private String name;

The Instructor Object Filename: ? package isical; public class Instructor { private String name; // The name of the student private String unit; // Which unit does the instructor belong to? public Instructor(String name, String unit) { this. name = name; this. unit = unit; } /* What can the student do? */ public String get. Name() { return name; // Returns the name } What does (s)he need to do? Get names from students and write down public String get. Unit() { return unit; // Returns the name of the unit } } 13

The method to do that work public void write. Names. Of. Students(Student[] list. Of.

The method to do that work public void write. Names. Of. Students(Student[] list. Of. Students) { for (int index = 0; index < list. Of. Students. length; { String name. Of. Student = list. Of. Students[index]. get. Name(); System. out. println(name. Of. Student); } } index++) 14

The final code Filename: Main. java package isical; public class Main { public static

The final code Filename: Main. java package isical; public class Main { public static void main(String[] args) { // Create an array of Students Student[] list. Of. Students = new Student[10]; // Create the students for (int student. Num = 0; student. Num < 10; student. Num++) { Student student = new Student("Student Number"+student. Num, student. Num); list. Of. Students[student. Num] = student; } // Create an instructor Instructor instructor = new Instructor("Instructor 1", "Some Unit Who cares"); // Now get the instructor to do the work instructor. write. Names. Of. Students(list. Of. Students); } } 15

What have we learnt so far? § The basic object oriented way of thinking

What have we learnt so far? § The basic object oriented way of thinking § Java – Basic file organization, packages – Class, constructor, methods – One example 16

Inheritance More general: Superclass MTech Student Living being Human being Faculty Bird JRF More

Inheritance More general: Superclass MTech Student Living being Human being Faculty Bird JRF More specific: Subclass § Subclasses can use state and behavior of the superclass § Java: each class can have one direct superclass, each superclass can have any number of subclasses 17

Student, Instructor and Person package isical; public class Person { private String name; //

Student, Instructor and Person package isical; public class Person { private String name; // Name of the person private int age; // Age of the person public Person(String name, int age) { this. name = name; this. age = age; } public String get. Name() { return name; } public int get. Age() { return age; } } 18

Student as a subclass of Person package isical; public class Student { Superclass Student

Student as a subclass of Person package isical; public class Student { Superclass Student extends Person private String name; // The name of the student private int roll. Number; // The numeric roll number of the student public Student(String name, int age) { super(name, age); // Call the constructor of the superclass } /* What can the student do? */ public String get. Name() { return name; // Returns the name } public int get. Roll. Number() { return roll. Number; } } 19

Student as a subclass of Person package isical; public class Student extends Person {

Student as a subclass of Person package isical; public class Student extends Person { Superclass Student extends Person private String name; // The name of the student private int roll. Number; // The numeric roll number of the student public Student(String name, int age) { super(name, age); // Call the constructor of the superclass } /* What can the student do? */ public String get. Name() { return name; // Returns the name } public int get. Roll. Number() { return roll. Number; } } 20

Student as a subclass of Person package isical; public class Student extends Person {

Student as a subclass of Person package isical; public class Student extends Person { Do we need it? private String name; // The name of the student private int roll. Number; // The numeric roll number of the student public Student(String name, int age) { super(name, age); // Call the constructor of the superclass } /* What can the student do? */ public String get. Name() { return name; // Returns the name } Do we need it? public int get. Roll. Number() { return roll. Number; } } 21

Student as a subclass of Person package isical; Inherited from Person public class Student

Student as a subclass of Person package isical; Inherited from Person public class Student extends Person { private String name; // The name of the student private int roll. Number; // The numeric roll number of the student public Student(String name, int age) { super(name, age); // Call the constructor of the superclass } /* What can the student do? */ public String get. Name() { return name; // Returns the name } public int get. Roll. Number() { return roll. Number; } Inherited from Person What else is inherited? } 22

Student as a subclass of Person package isical; public class Student extends Person {

Student as a subclass of Person package isical; public class Student extends Person { State not in Person private int roll. Number; // The numeric roll number of the student public Student(String name, int age) { super(name, age); // Call the constructor of the superclass } /* What can the student do (more than what it inherits by being a Person) */ public int get. Roll. Number() { return roll. Number; } } Now compile, run and verify that a Student can still tell his/her name! Similarly, modify the code so that the Instructor also extends Person 23

Overriding a super method § Now consider the following functionality in Person public class

Overriding a super method § Now consider the following functionality in Person public class Person { … … private String profession; // Profession of the person … … public void set. Profession(String profession) { this. profession = profession; } public String get. Profession() { return profession; } } The Student would automatically inherit the same! 24

The Student does it differently! public class Student extends Person { … … private

The Student does it differently! public class Student extends Person { … … private String institute; // The name of the institute private String program; // The name of the program … … // Overrides isical. Person. get. Profession public String get. Profession() { return "Student of " + program + " at " + institute; } } 25

Abstract class § Abstract method: too abstract to provide an implementation – Name of

Abstract class § Abstract method: too abstract to provide an implementation – Name of a living being – Area of a shape (can be circle, rectangle, … ) § Abstract class: Some conceptual objects with one or more abstract methods – Concrete subclasses are derived from abstract class 26

Living. Being package isical; public abstract class Living. Being { Define an abstract class

Living. Being package isical; public abstract class Living. Being { Define an abstract class public abstract String get. Name(); } public class Person extends Living. Being { …… …… } Abstract method Derived class Must implement the inherited abstract method 27

Interface Methods Outside world Object Interface § Methods form the object’s interface with the

Interface Methods Outside world Object Interface § Methods form the object’s interface with the outside world § A group of methods to define a set of common functionalities An interface 28

An Interface Movable package isical; public interface Movable { public int move. Position(int position);

An Interface Movable package isical; public interface Movable { public int move. Position(int position); Any movable object must have this functionality } public class Person extends Living. Being implements Movable { //. . . @Override public int move. Position(int position) { return position+1; } In general a person moves one step } 29

Abstract class vs Interface § Abstract classes, superclasses and derived classes are supposed to

Abstract class vs Interface § Abstract classes, superclasses and derived classes are supposed to be of the same type of objects – Living being Human, Bird – House Bungalow, Hut § An Interface defines a set of functionalities – House: class, Air conditioning: interface – Some houses implement air conditioning § Proper use is left to the developers 30

Parameterization § Array of 10 integers : int[10] § Array of 10 booleans :

Parameterization § Array of 10 integers : int[10] § Array of 10 booleans : boolean[10] What are these? Of what type? Parameterized classes § List of Integers : Array. List<Integer> § Collection of Books : Hash. Map<String, Book> 31

Test. java – check things out package isical; import java. util. Array. List; public

Test. java – check things out package isical; import java. util. Array. List; public class Test { public static void main(String[] args) { Array. List<String> array. List = new Array. List<String>(); array. List. add("First"); array. List. add("Second"); array. List. add("Third"); array. List. add("Another"); array. List. add("Yet another"); System. out. println(array. List. size()); System. out. println(array. List. get(3)); System. out. println(array. List. get(8)); array. List. set(4, "XYZ"); System. out. println(array. List. get(4)); } } 32

Also check out Hash. Map import java. util. Hash. Map; // REST OF THE

Also check out Hash. Map import java. util. Hash. Map; // REST OF THE BODY OF THE CLASS SHOULD BE HERE… Hash. Map<Integer, String> map = new Hash. Map<Integer, String>(); map. put(1, "Prateek Pandey"); // Put your roll numbers // Now get the value given the key System. out. println("Roll number: " + 1 + ", Name: " + map. get(1)); 33

A Basic Name Directory package isical; /** * This class stores the names of

A Basic Name Directory package isical; /** * This class stores the names of students per batch */ public abstract class Name. Directory { /** * Adds a student to the specified batch * * @param student * @param batch. Name */ public abstract void add. Student(Student student, String batch. Name); /** * Given a batch name and student name, finds the student in the batch * * @param batch. Name * @param student. Name * @return the student object if found, null otherwise */ public abstract Student get. Student(String batch. Name, String student. Name); } 34

Implementation : Dyn. Name. Directory package isical; public class Dyn. Name. Directory extends Name.

Implementation : Dyn. Name. Directory package isical; public class Dyn. Name. Directory extends Name. Directory { States? @Override public void add. Student(Student student, String batch. Name) { // TODO: Implement it } @Override public Student get. Student(String batch. Name, String student. Name) { // TODO: Implement it return null; } } 35

Implementation : Dyn. Name. Directory package isical; public class Dyn. Name. Directory extends Name.

Implementation : Dyn. Name. Directory package isical; public class Dyn. Name. Directory extends Name. Directory { // Internal storing mechanism private Hash. Map<String, Array. List<Student>> directory = new Hash. Map<String, Array. List<Student>>(); @Override public void add. Student(Student student, String batch. Name) { // TODO: Implement it } @Override public Student get. Student(String batch. Name, String student. Name) { // TODO: Implement it return null; } } 36

Implementation : Dyn. Name. Directory package isical; public class Dyn. Name. Directory extends Name.

Implementation : Dyn. Name. Directory package isical; public class Dyn. Name. Directory extends Name. Directory { // Internal storing mechanism private Hash. Map<String, Array. List<Student>> directory = new Hash. Map<String, Array. List<Student>>(); Key (name) String Array. List Hashmap Hash function Key, Value Student 11 Student 12 … … Key, Value Student 21 Student 22 … … Key, Value 37

Implementation : add. Student package isical; public class Dyn. Name. Directory extends Name. Directory

Implementation : add. Student package isical; public class Dyn. Name. Directory extends Name. Directory { private Hash. Map<String, Array. List<Student>> directory = new Hash. Map<String, Array. List<Student>>(); @Override public void add. Student(Student student, String batch. Name) { // Check if the batch exists Array. List<Student> list = directory. get(batch. Name); // If does not exist, should return null if (list == null) { list = new Array. List<Student>(); } // Now add the student list. add(student); // Now put the list back into the hash map directory. put(batch. Name, list); } } 38

Implementation : get. Student public class Dyn. Name. Directory extends Name. Directory { private

Implementation : get. Student public class Dyn. Name. Directory extends Name. Directory { private Hash. Map<String, Array. List<Student>> directory = new Hash. Map<String, Array. List<Student>>(); @Override public Student get. Student(String batch. Name, String student. Name) { // Get the list corresponding to the batch Array. List<Student> list. Of. Students = directory. get(batch. Name); // If does not exist, then return null anyway if (list. Of. Students == null) return null; // Otherwise find the student by iterating over the students for (Student student : list. Of. Students) { String name = student. get. Name(); if (name. equals. Ignore. Case(student. Name)) { return student; } } // If nobody is found, return null; } } Iterator 39

Collections, Lists Iterable, Collection Abstract Collection List Set Abstract List Array. List Vector Abstract

Collections, Lists Iterable, Collection Abstract Collection List Set Abstract List Array. List Vector Abstract Set …… … Hash. Set Tree. Set … 40

Generics package isical; /** * A pair of two elements. First one is of

Generics package isical; /** * A pair of two elements. First one is of type T 1, the second one is of type T 2 * * @param <T 1> * @param <T 2> */ public class Pair<T 1, T 2> { private T 1 element 1; private T 2 element 2; Write the methods to set the first and second elements public Pair(T 1 e 1, T 2 e 2) { element 1 = e 1; element 2 = e 2; } public T 1 get. First. Element() { return element 1; } Is one pair comparable to another? public T 2 get. Second. Element() { return element 2; } } 41

Generics package isical; public class Pair<T 1, T 2> { private T 1 element

Generics package isical; public class Pair<T 1, T 2> { private T 1 element 1; private T 2 element 2; What do we need for comparing? } public class Pair<T 1 extends Comparable<T 1>, T 2> implements Comparable<Pair<T 1, T 2>> { @Override public int compare. To(Pair<T 1, T 2> o) { // Simply compare based on element 1, because T 1 is comparable return element 1. compare. To(o. get. First. Element()); } } 42

Advanced in-class Exercise § Implement your own List, called My. List with basic dynamic

Advanced in-class Exercise § Implement your own List, called My. List with basic dynamic element addition feature § Should support methods to – – Check current size (number of elements) Add an element Get the element at position i Set an element at position i § Generic class definition: public class My. List<T> { } 43