Object-Orientation. Classes Lecture 5. Classes. State and Behaviour. Instance Variables. Object vs. Classes

Similar documents
Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Principles of Object Oriented Programming. Lecture 4

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Introduction to Programming Using Java (98-388)

About this exam review

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

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

Object-Oriented Programming Concepts

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 4 Defining Classes I

Lecture 5: Methods CS2301

Sri Vidya College of Engineering & Technology

Lecture 18 Tao Wang 1

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

1B1b Classes in Java Part I

CMSC 132: Object-Oriented Programming II

MIDTERM REVIEW. midterminformation.htm

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

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

ECE 122. Engineering Problem Solving with Java

Chapter 10 Introduction to Classes

C++ (Non for C Programmer) (BT307) 40 Hours

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Objects and Classes: Working with the State and Behavior of Objects

Announcements/Follow-ups

Fundamental Java Methods

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Administration. Classes. Objects Part II. Agenda. Review: Object References. Object Aliases. CS 99 Summer 2000 Michael Clarkson Lecture 7

EECS168 Exam 3 Review

Anatomy of a Class Encapsulation Anatomy of a Method

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban

What is an algorithm?

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

CS1004: Intro to CS in Java, Spring 2005

What is an algorithm?

Computer Science II (20073) Week 1: Review and Inheritance

Making New instances of Classes

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci)

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Java and OOP. Part 2 Classes and objects

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Programming II (CS300)

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Programming II (CS300)

Chapter 4: Writing Classes

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

ECE 122. Engineering Problem Solving with Java

CS 1316 Exam 1 Summer 2009

Classes Classes 2 / 35

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Computer Science II. OO Programming Classes Scott C Johnson Rochester Institute of Technology

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

CMSC 341. Nilanjan Banerjee

BM214E Object Oriented Programming Lecture 8

The Notion of a Class and Some Other Key Ideas (contd.) Questions:

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Encapsulation. You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methods

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Java Magistère BFA

CS1004: Intro to CS in Java, Spring 2005

ECE 122. Engineering Problem Solving with Java

Abstract Classes and Interfaces

Object Oriented Design

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Overview CSE 142. Naming Revisited Declarations. Defining Parts of Objects

This Week. Fields and Variables. W05 Example 1: Variables & Fields. More on Java classes. Constructors. Modifiers

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Object Oriented Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Java Fundamentals (II)

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Creating and Using Objects

CS 1331 Exam 1 ANSWER KEY

Day 2. COMP 1006/1406A Summer M. Jason Hinek Carleton University

CS-202 Introduction to Object Oriented Programming

Midterms Save the Dates!

COMP-202. Objects, Part III. COMP Objects Part III, 2013 Jörg Kienzle and others

An Introduction to C++

ECE 122. Engineering Problem Solving with Java

Software Systems Development Unit AS1: Introduction to Object Oriented Development

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Objects as a programming concept

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Fast Introduction to Object Oriented Programming and C++

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:

CS 1331 Exam 1. Fall Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score.

Transcription:

CP4044 Lecture 5 1 Classes Lecture 5 Object-Orientation Object-oriented design (OOD) Models real-world objects Models communication among objects Encapsulates data (attributes) and functions (behaviors) Information hiding Communication through well-defined interfaces Object-oriented language Used to implement OO designs Programming is called object-oriented programming (OOP) Java We will not be looking at OO in depth just enough to facilitate systems programming in Java CP4044 Lecture 5 2 State and Behaviour Attributes define the state of an object Called instance variables in Java Attributes have a name, type and value e.g. a car might have an attribute with the name bodycolour of type colour and has the value red Methods define the behaviour of an object Similar to functions or procedures in other programming languages Methods have names that should indicate their behaviour e.g. a car might have a method moveforward CP4044 Lecture 5 3 Classes Definition Every object belongs to a group of objects of the same type called the object s class. A class defines the types of states and behaviour belonging to a group of objects Examples My Ferrari Belongs to the car class Wolverhampton Wanderers Football club class MT008 Lecture theatre class CP4044 Lecture 5 4 Object vs. Classes Class A template that defines attributes and methods Written by programmer as part of program Cannot be altered during program execution Is named by a class name Object Must belong to some class Exists whilst the program is executing Must be declared and constructed by a program Has attributes with values and methods that can execute Class defines these Referenced by an identifier (variable name) CP4044 Lecture 5 5 Instance Variables Scope: Instance variables may be accessed by all the methods in the class Variables declared in methods are local to the method and cannot be seen outside it more on this next week. All variables in Java must be initialised before use When a class is instantiated (i.e. object is created) the default values of its variables are 0 or null This is not the case with local variables, as we shall CP4044 Lecture 5 6

CP4044 Lecture 5 7 Creating Objects An object is an instance of a class An object is constructed or instantiated from a class Instantiation is done with the new operator An object reference is used to refer to an object Declaration of a TV object reference called mytv Construction and assignment of a TV object TV mytv; mytv = new TV(); new Operator TV constructor Parameters Used for passing data to a method Return type Defines the type of data to be passed from the method. Keyword void is used here if methods returns no data. Anatomy of a Method int calculatearea(int w, int h) { int area = w * h; return area; Return statement Used for passing data from the method. Omitted for void methods CP4044 Lecture 5 8 Parameters values Are used to transfer data to a method Return value Contains the data passed from the method. Here it is copied into a variable Calling a Method int calculatearea(int w, int h) { int area = w * h; return area; int area; area = calculatearea(2, 5); System.out.println("Area =" + area); A non-void method can be called anywhere an expression of the same type is permitted. e.g. from within calculations CP4044 Lecture 5 9 Overloaded Methods It is possible to have more than one method with the same name. Called overloading methods Must have different parameter types Must have the same return type double calculatecost(double price) { double taxrate = 1.175; return price * taxrate; Method uses default tax rate double calculatecost(double price, double taxrate) { return price * taxrate; User specifies tax rate CP4044 Lecture 5 10 Accessing Methods and Attributes An object reference acts as an alias for an object Object references can be used to access instance variables and methods Object-reference.variable-name Object-reference.method-name Examples: mytv.channel = 1; Sets the channel instance variable of the mytv object to the value 1 mytv.press2(); Calls the press2 method of the mytv object CP4044 Lecture 5 11 Types of Variables & Scope Instance variables Defined inside a class, but outside all methods Used to store the state of an object Can be accessed from any method in the class Automatically initialised - given default values Parameter variables Defined in a method header Used to pass data to a method Can only be accessed from the method they are defined in Initialised by values from the caller Local variables Defined inside a method Used for storing intermediate/temporary values Can only be accessed from the method they are defined in Must be explicitly initialised before they can be used CP4044 Lecture 5 12

CP4044 Lecture 5 13 Resolving Ambiguity The this reference points to the current object. this.name therefore references the instance variable called name belonging to the current object. Constructors Constructors Similar to methods and invoked when an object is created Used to perform additional initialisation Constructor has same name as class No return type Can be overloaded This line copies the value from the parameter variable to the instance variable. class Person { String name; void setname(string name) { this.name = name; Default Constructor Constructor without parameters Invoked if no other constructor is specified when object is created Automatically created by Java if not explicitly declared CP4044 Lecture 5 14 Default Constructors Constructors are like methods: But have no return type (not even void) Must have exactly the same name as the class Can be overloaded Default constructor has no parameters Used to give initial values to instance variables If you do not supply a default constructor, the compiler will generate one for you. But its behaviour might not be what you want Parameterised Constructors Parameterised constructors require the caller to supply parameters Parameters are used to initialise instance variables Saves the caller calling update methods just after the default constructor This is what you have to do in some semi-oo languages such as VB 6. Constructor uses similar syntax to update methods The this reference is used to resolve ambiguity Can have various different overloaded versions of constructors for complex classes Allow the user to specify some parameters, but use defaults for others. CP4044 Lecture 5 15 CP4044 Lecture 5 16 House Class House Class Instance variables 1 2 3 class House { int number; String street; 1 2 3 class House { int number; String street; 13 14 15 int getnumber() { return number; Default constructor Parameterised constructor 4 House() { 5 number = 0; 6 street = "not known"; 7 8 House(int number, 9 String street) { 10 this.number = number; 11 this.street = street; 12 13 4 5 6 7 8 9 10 11 12 House() { number = 0; street = "not known"; House(int number, String street) { this.number = number; this.street = street; 16 17 18 void setnumber(int number){ this.number = number; 19 String getstreet() { 20 return street; 21 22 void setstreet(string street){ 23 this.street = street; 24 25 CP4044 Lecture 5 17 CP4044 Lecture 5 18

CP4044 Lecture 5 19 Data Integrity Problems We cannot trust users of our classes to use them in the way we intended. The internal state of an object get damaged We need to maintain the integrity of the data TV ison : boolean channel : int TV() TV kevstv; kevstv = new TV(); kevstv.channel = 2; Data Hiding Ensure integrity of the data Other classes cannot directly access the data, thus cannot corrupt it. Hide internal workings of class Provides a minimal interface. Reduces complexity when using the class or visualising a whole system. Others can treat class as a black box. They don t need to know how it works, just assume it meets specifications. TV kevstv; kevstv = new TV(); kevstv.channel = -768; We need to make sure the channel is between 1 and 3 CP4044 Lecture 5 20 Public and Private Members Instance variables and methods are preceded with public or private keywords. Defines the interface between the class and other classes. i.e. the means of communication private class members May only be accessed from the class itself. Public and Private Members public class Person { private String name; public Person () { this.name = "unknown"; public void setname(string name) { this.name = name; public String getname() { return name; public class members May be accessed from any class. invalid Person p1 = new Person(); p1.name = "Billy"; valid Person p1 = new Person(); p1.setname("billy"); CP4044 Lecture 5 21 CP4044 Lecture 5 22 Protected Members In some examples you will see protected in place of public or private. This is something we are not ready to cover yet. For now assume protected does the same thing as private. This is effectively what it does for the types of programs we are looking at on this module. Rules for Data Hiding Don t allow direct external access to instance variables. Make all instance variables private. Provide public methods to access data. Validate data before assigning to instance variables. Provide other methods on a need to know basis. Only make public the methods useful outside the class. Keep the interface as simple as possible. CP4044 Lecture 5 23 CP4044 Lecture 5 24

CP4044 Lecture 5 25 Rational Number Class Worked Example Development of a Rational Class For storing fractions, e.g. 1/7 Cannot be stored accurately as floating point numbers Store as a pair of integers Class provides methods for operating on rational numbers CP4044 Lecture 5 26 Rational Number Operators Test Harness public class RatDemo1 { RatNumber k = new RatNumber(3, 4); k.show(); Object construction Method call We should reduce results to their lowest terms (50, 100) (1,2) CP4044 Lecture 5 27 CP4044 Lecture 5 28 Rational Number Class public class RatNumber { int num; int den; public RatNumber(int x, int y) { num = x; den = y; Instance variables constructor Results C:\>javac RatNumber.java C:\>javac RatDemo1.java C:\>java RatDemo1 (3/4) public String tostring() { return "(" + num + "/" + den + ")"; Method CP4044 Lecture 5 29 CP4044 Lecture 5 30

CP4044 Lecture 5 31 New Test Harness public class RatDemo { RatNumber k, l, m; k = new RatNumber(3, 4); l = new RatNumber(5, 6); m = k.add(l); System.out.println( m.tostring() ); Call by value Add Method Implementation public RatNumber add(ratnumber a) { result = new RatNumber(0,0); result.num = num * a.den + a.num * den; result.den = den * a.den; return result; (38/24) CP4044 Lecture 5 32 Alternative Add Method Implementation public RatNumber add(ratnumber a) { return new RatNumber( num * a.den + a.num * den, den * a.den); CP4044 Lecture 5 33 Adding an Integer to a Rational public RatNumber add(int a) { return new RatNumber(num + a * den, den); public class RatDemo { RatNumber k, l, m; k = new RatNumber(3, 4); l = new RatNumber(5, 6); m = K.add(L); System.out.println( m ); m = m.add(2); System.out.println( m ); (38/24) (86/24) CP4044 Lecture 5 34 Simplification private RatNumber simplify(ratnumber a) { int gcd; gcd = euclid(a.num, a.den); a.num /= gcd; a.den /= gcd; return a; private int euclid(int a, int b) { if (b == 0) return a; else return euclid(b, a % b); CP4044 Lecture 5 35 Euclid is a Recursive Method private int euclid(int a, int b) { if (b == 0) return a; euclid(27,45) else return euclid(45,27) return euclid(b, a % b); euclid(45,27) return euclid(27,18) euclid(27,18) return euclid(18,9) euclid(18,9) return euclid(9,0) euclid(9,0) return 9 CP4044 Lecture 5 36

CP4044 Lecture 5 37 Simplification public RatNumber add(ratnumber a) { return simplify (new RatNumber( num * a.den + a.num * den, den * a.den)); public RatNumber add(int a) { return simplify ( new RatNumber(num + a * den, den)); Array of Rationals public class RatDemo { RatNumber[] nums; nums = new RatNumber[10]; (3/6) (4/7) (5/8) 0.5 0.571428 0.625 for (int i = 0; i < 10; i++) { (3/9) 0.333333 int j = i % 3; (4/10) 0.4 nums[i] = new RatNumber(j + 3, i + 6); (5/11) 0.454545 for (int i = 0; i < 10; i++) System.out.println(nums[i].toString() (3/12) 0.25 (4/13) 0.307692 (5/14) 0.357142 +"\t"+nums[i].todouble() );(3/15) 0.2 CP4044 Lecture 5 38 Sorting import java.util.arrays; Arrays.sort( array, comparator ); public interface Comparator<T> { public abstract int compare( T obj1, T obj2 ); public abstract boolean equals(object obj); CP4044 Lecture 5 39 Sorting import java.util.comparator; public class AscOrder implements Comparator<RatNumber> { // Method to compare RatNumber objects. public int compare(ratnumber a, RatNumber b) { return (a.num * b.den)-(a.den * b.num); Define the method compare( a, b ) to return +ve int if a > b -ve int if a < b 0 if a equals b CP4044 Lecture 5 40 Sorted RatNumber Objects Arrays.sort(nums, new AscOrder); System.out.println("Ascending order"); for(int i=0;i<10;i++) System.out.println(nums[i]+"\t"+nums[i].toDecimal(); Ascending order: (3/15) 0.2 (3/12) 0.25 (4/13) 0.3076923076923077 (3/9) 0.3333333333333333 (5/14) 0.35714285714285715 (4/10) 0.4 (5/11) 0.45454545454545453 (3/6) 0.5 (4/7) 0.5714285714285714 (5/8) 0.625 CP4044 Lecture 5 41 Summary Object orientation State and behavior Data hiding public and private member variables Instantiating a class - objects User-defined classes Constructors, instance variables, methods Developing a class - RatNumber Using a Test Harness to develop a class Sorting arrays CP4044 Lecture 5 42