Software and Programming I. Classes and Arrays. Roman Kontchakov / Carsten Fuhs. Birkbeck, University of London

Similar documents
Inheritance and Subclasses

Collections and Maps

Arrays and Basic Algorithms

4CCS1PRP, Programming Practice 2012 Lecture 6: Arrays - Part 1

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Introduction to Inheritance

Loops and Expression Types

More on Objects and Classes

Polymorphism. return a.doublevalue() + b.doublevalue();

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Collections Algorithms

INHERITANCE. Spring 2019

Input-Output and Exception Handling

Intro to Computer Science 2. Inheritance

Object-Oriented Programming in Java

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Inheritance Advanced Programming ICOM 4015 Lecture 11 Reading: Java Concepts Chapter 13

Java Fundamentals (II)

Inheritance, Polymorphism, and Interfaces

Practice for Chapter 11

Java Magistère BFA

Exam Duration: 2hrs and 30min Software Design

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Inheritance. Transitivity

CLASS DESIGN. Objectives MODULE 4

More about inheritance

The class Object. Lecture CS1122 Summer 2008

Chapter 5 Object-Oriented Programming

Inheritance (Part 5) Odds and ends

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

Inheritance (P1 2006/2007)

C12a: The Object Superclass and Selected Methods

Objects and Classes. Lecture 10 of TDA 540 (Objektorienterad Programmering) Chalmers University of Technology Gothenburg University Fall 2017

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Programming overview

Lecture 4: Extending Classes. Concept

Abstract Classes and Interfaces

CH. 2 OBJECT-ORIENTED PROGRAMMING

Introduction to Programming Using Java (98-388)

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

CS-202 Introduction to Object Oriented Programming

Distributed Systems Recitation 1. Tamim Jabban

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Handout 9 OO Inheritance.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Overriding methods. Changing what we have inherited from e.g. Object

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

COE318 Lecture Notes Week 8 (Oct 24, 2011)

Java Classes, Inheritance, and Interfaces

Chapter Goals. Chapter 9 Inheritance. Inheritance Hierarchies. Inheritance Hierarchies. Set of classes can form an inheritance hierarchy

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions

Inheritance and Polymorphism

CS260 Intro to Java & Android 03.Java Language Basics

ITI Introduction to Computing II

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

Super-Classes and sub-classes

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

ARRAYS and ARRAYLISTS

Instructions. Quiz #2. Name: Solutions Student Number: Signature:

COMP 250. Lecture 32. polymorphism. Nov. 25, 2016

Inheritance and Interfaces

Questions Answer Key Questions Answer Key Questions Answer Key

What is Inheritance?

Objectives. Inheritance. Inheritance is an ability to derive a new class from an existing class. Creating Subclasses from Superclasses

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

Interfaces. Chapter Java Interfaces

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Branching and Boolean Expressions

25. Generic Programming

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Chapter 11: Collections and Maps

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Java Object Oriented Design. CSC207 Fall 2014

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Lecture 10: Interfaces

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Software and Programming 1

index.pdf January 21,

Chapter 1: Introduction to Computers, Programs, and Java

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

TeenCoder : Java Programming (ISBN )

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Chapter 14 Abstract Classes and Interfaces

Check out Polymorphism from SVN. Object & Polymorphism

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

Methods Common to all Classes

ITI Introduction to Computing II

ITI Introduction to Computing II

type conversion polymorphism (intro only) Class class

Transcription:

Software and Programming I Classes and Arrays Roman Kontchakov / Carsten Fuhs Birkbeck, University of London

Outline Class Object Interfaces Arrays Sections 9.5 9.6 Common Array Algorithms Sections 6.1 6.4 slides are available at www.dcs.bbk.ac.uk/ roman/sp1 SP1 2018-09 1

Overriding, Inheritance and Polymorphism a subclass inherits all methods that it does not override a subclass method overrides a public method from a superclass if both methods have the same signature a subclass can override a superclass method by providing a new implementation polymorphism: the type of the reference determines which method signatures we may call the type of the actual object determines which method implementation is invoked (checked at compile-time) (at run-time) SP1 2018-09 2

Overriding, Inheritance and Polymorphism: Example 1 public class A { 2 public int f() { return 1; } 3 public int g() { return 2; } 4 } 5 public class B extends A { // g() is inherited from A 6 public int f() { return 3; } // f() is overridden 7 } 8... 9 A a = new A(); 10 System.out.println(a.f() + " " + a.g()); // prints 1 2 11 B b = new B(); 12 System.out.println(b.f() + " " + b.g()); // prints 3 2 13 A c = new B();// c provides A s methods, uses B s code 14 System.out.println(c.f() + " " + c.g()); // prints 3 2 SP1 2018-09 3

The Object Class every class declared without the explicit extends clause automatically extends the class Object class Object has method String tostring(), which one can override 1 public class BankAccount { 2... 3 public String tostring() { 4 return "account " + name + 5 ", balance = " + balance; 6 } 7 } SP1 2018-09 4

Overriding tostring() 1 public class CurrentAccount { 2... 3 public String tostring() { 4 return "current " + super.tostring(); 5 } 6 } 7 public class SavingsAccount { 8... 9 public String tostring() { 10 return "savings " + super.tostring() + 11 ", interest rate = " + interestrate; 12 } 13 } SP1 2018-09 5

Using Object.toString() the method tostring() is called, e.g., in System.out.println 1 public static void printall(bankaccount[] accounts) { 2 for (BankAccount a: accounts) 3 System.out.println(a); 4 } the implementation of method println(object obj) invokes obj.tostring() which tostring() implementation is invoked depends on the run-time type of obj (polymorphism) SP1 2018-09 6

Polymorphism in Action 1 BankAccount[] arr = new BankAccount[2]; 2 arr[0] = new BankAccount("B"); 3 arr[1] = new SavingsAccount("A",0.3); 4 printall(arr); arr BankAccount[ ] [0] = [1] = System.out.println(arr[0]) BankAccount.toString() System.out.println(arr[1]) SavingsAccount.toString() BankAccount name = "B" balance = 0.0 SavingsAccount BankAccount name = "A" balance = 0.0 interestrate = 0.3 minbalance = 0.0 account B, balance = 0.0 savings account A, balance = 0.0, interest rate = 0.3 SP1 2018-09 7

More Methods of Object boolean equals(object obj) indicates whether some other object is equal to this one int hashcode() returns a hash code value for the object (used in collections) Class getclass() returns the run-time class of an object SP1 2018-09 8

Overloading Methods (and constructors) can have the same name (provided their signatures (i.e., name and parameter types) are different) 1 public class BankAccount { 2 //... 3 public BankAccount(String name) { 4 this.name = name; 5 this.balance = 0; 6 } 7 public BankAccount(BankAccount a) { 8 this.name = "copy of " + a.name; 9 this.balance = a.balance; 10 } 11 } SP1 2018-09 9

Overloading (2) 1 // constructor 1: BankAccount(String) 2 BankAccount a = new BankAccount("A"); 3 a.deposit(100); 4 // constructor 2: BankAccount(BankAccount) 5 BankAccount b = new BankAccount(a); a BankAccount name = "A" balance = 100.0 BankAccount b name = "copy of A" balance = 100.0 NB: compile-time types of arguments determine which constructor is called SP1 2018-09 10

Interface Types Java does not support multiple inheritance from classes an interface type declares a set of methods and their signatures unlike a class, an interface type provides no implementation 1 public interface Measurable { 2 double getmeasure(); // interface methods are 3 // always public 4 // any other access modifier 5 // makes no sense 6 } SP1 2018-09 11

Implementing an Interface 1 public class BankAccount implements Measurable { 2... 3 public double getmeasure() { 4 return getbalance(); 5 } 6 } 7 8 public class Country implements Measurable { 9... 10 public double getmeasure() { 11 return getarea(); 12 } 13 } SP1 2018-09 12

Using an Interface 1 public static double summeasures(measurable[] ma) { 2 double result = 0; 3 for (Measurable m: ma) 4 result = result + m.getmeasure(); 5 return result; 6 } ma may contain instances of BankAccount, Country or any classes that implement Measurable NB: these classes are subtypes of Measurable which implementation of m.getmeasure() is determined by m s run-time type (polymorphism) SP1 2018-09 13

The Interface Comparable This interface imposes a total ordering on the objects of each class that implements it This ordering is referred to as the class s natural ordering 1 public interface Comparable<T> { // T is a type name 2 int compareto(t other); // (a generic interface) 3 } o1.compareto(o2) compares objects in the natural ordering: < 0 if o1 is less than o2 in the natural ordering == 0 if o1 equals o2 > 0 if o1 is greater than o2 in the natural ordering SP1 2018-09 14

The Interface Comparable (2) 1 public class BankAccount 2 implements Comparable<BankAccount> { 3... 4 public int compareto(bankaccount other) { 5 if(this.getbalance() - other.getbalance() > 0) 6 return 1; 7 if(this.getbalance() - other.getbalance() < 0) 8 return -1; 9 return 0; 10 } 11 } SP1 2018-09 15

The Interface Comparable (3) 1... 2 BankAccount[] accounts = new BankAccount[3]; 3... 4 java.util.arrays.sort(accounts); Arrays.sort(...) calls int compareto(bankaccount other) to compare two BankAccount objects NB: String and many other standard classes implement this interface SP1 2018-09 16

Nested Loops 1 for (int r = 8; r >= 1; r--) { 2 for (char c = a ; c <= h ; c++) // char is 3 // an integral datatype 4 System.out.print(" " + c + r + " "); 5 System.out.println(); 6 } a8 b8 c8 d8 e8 f8 g8 h8 a7 b7 c7 d7 e7 f7 g7 h7 a6 b6 c6 d6 e6 f6 g6 h6 a5 b5 c5 d5 e5 f5 g5 h5 a4 b4 c4 d4 e4 f4 g4 h4 a3 b3 c3 d3 e3 f3 g3 h3 a2 b2 c2 d2 e2 f2 g2 h2 a1 b1 c1 d1 e1 f1 g1 h1 SP1 2018-09 17

Arrays an array collects a sequence of values of the same type 1 // empty array of 5 students 2 Student[] students = new Student[5]; 3 // list of initial values 4 String[] data = { "I", "V", "X", "L" }; students data NB: why is this diagram not entirely accurate? String[ ] [0] = "I" [1] = "V" [2] = "X" [3] = "L" Student[ ] [0] = null [1] = null [2] = null [3] = null [4] = null SP1 2018-09 18

Array Elements individual elements in an array are accessed by an integer index i, using the notation data[i] an array element can be used in expressions like any other variable the elements of arrays are numbered starting at 0 use the expression data.length to find the number of elements in an array 1 int[] data = { 2, 3, 5, 7, 11 }; 2 for (int i = 0; i < data.length / 2; i++) 3 data[data.length - 1 - i] = data[i]; SP1 2018-09 19

The Length of Arrays is Fixed come up with a guess on the maximum number of elements and keep a companion variable for the current size 1 final int LENGTH = 100; // max number of elements 2 // partially filled array 3 double[] data = new double[length]; 4 int currentsize = 0; // the actual number of elements 5 data[currentsize] = 42; // insert 42 6 currentsize++; // increase the number of elements 0 currentsize data[0] data[1] data[2]... data[0] = 42 data[1] data[2] data[length-1] data[length-1] SP1 2018-09 20 1 currentsize...

Partially Filled Arrays 1 Scanner in = new Scanner(System.in); 2 while (in.hasnextdouble()) // read all doubles 3 if (currentsize < data.length) { 4 // currentsize is the first position 5 // available 6 data[currentsize] = in.nextdouble(); 7 // update the actual number of elements 8 currentsize++; 9 } 10 // the actual elements are indexed 11 // from 0 to currentsize-1 12 for (int i = 0; i < currentsize; i++) 13 System.out.println(data[i]); SP1 2018-09 21

Partially Filled Arrays: Removing an Element removing the element at position pos data[0]... data[pos-1] data[pos] data[pos+1]... data[currentsize-1]... data[length-1] data[0]... data[pos-1] data[pos]... data[currentsize-2] data[currentsize-1]... data[length-1] 1 for (int i = pos; i < currentsize - 1; i++) 2 data[i] = data[i+1]; 3 currentsize--; // update the actual number of elements SP1 2018-09 22

Partially Filled Arrays: Inserting an Element inserting a newelement at position pos data[0]... data[pos-1] data[pos]... data[currentsize-1] data[0]... data[pos-1] newelement data[pos+1]... data[currentsize] data[currentsize] 1 if (currentsize < data.length) { // check space 2 for (int i = currentsize; i > pos; i--) 3 data[i] = data[i-1]; 4 data[pos] = newelement; // place into array 5 currentsize++; // update the number of elements 6 } SP1 2018-09 23

Bubble Sort: Idea Repeatedly step through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted SP1 2018-09 24

Bubble Sort: Example pass 1: ( 5 1 4 2 8 ) ( 1 5 4 2 8 ), swap ( 1 5 4 2 8 ) ( 1 4 5 2 8 ), swap ( 1 4 5 2 8 ) ( 1 4 2 5 8 ), swap ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) pass 2: ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) ( 1 4 2 5 8 ) ( 1 2 4 5 8 ), swap ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) ( 1 2 4 5 8 ) The array is already sorted, but the algorithm does not know if it is completed It needs one whole pass without any swap to know it is sorted NB: does it need to go until the very end on every pass? NB: how many steps does the algorithm require? best sorting algorithms require O(n log n) steps SP1 2018-09 25

Bubble Sort: Implementation 1 boolean swapped = false; 2 do { 3 swapped = false; 4 // start from 1, not 0! 5 for (int i = 1; i < data.length; i++) { 6 if (data[i-1] > data[i]) { 7 double t = data[i-1]; 8 data[i-1] = data[i]; 9 data[i] = t; 10 swapped = true; 11 } 12 } 13 } while (swapped); SP1 2018-09 26

Take Home Messages every class automatically extends the class Object an interface type declares a set of methods and their signatures an array index in an array data must be >= 0 and < data.length arrays can occur as method parameters and return values (passing by reference ) with a partially filled array, keep a companion variable for the current size SP1 2018-09 27