Classes and Objects. Again: Distance between points within the first quadrant. José Valente de Oliveira 4-1

Similar documents
An introduction to Java II

Overview. Another application of Interfaces: the Strategy Design Pattern. n Java interfaces

Chapter 11. Friends, Overloaded Operators, and Arrays in Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Java Expressions & Flow Control

Chapter 10. Defining Classes. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

JCF: case studies. Bruce Eckel, Thinking in Java, 4th edition, PrenticeHall, New Jersey, cf.

Recursion. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Review: Method Frames

Exceptions. Your computer takes exception. The Exception Class. Causes of Exceptions

Java Inheritance. Class ADT (Abstract Data Type) Interface. Classes implement the concept of ADT: Interfaces define interaction contracts: Rui Moreira

CS 11 C track: lecture 1

10/23/18. File class in Java. Scanner reminder. Files. Opening a file for reading. Scanner reminder. File Input and Output

Python Programming: An Introduction to Computer Science

Java net programming II

Overview. Chapter 18 Vectors and Arrays. Reminder. vector. Bjarne Stroustrup

Analysis Metrics. Intro to Algorithm Analysis. Slides. 12. Alg Analysis. 12. Alg Analysis

CMPT 125 Assignment 2 Solutions

Ones Assignment Method for Solving Traveling Salesman Problem

Chapter 8. Strings and Vectors. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Pseudocode ( 1.1) Analysis of Algorithms. Primitive Operations. Pseudocode Details. Running Time ( 1.1) Estimating performance

Outline and Reading. Analysis of Algorithms. Running Time. Experimental Studies. Limitations of Experiments. Theoretical Analysis

Threads and Concurrency in Java: Part 1

Threads and Concurrency in Java: Part 1

Chapter 8. Strings and Vectors. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

CIS 121 Data Structures and Algorithms with Java Spring Stacks and Queues Monday, February 12 / Tuesday, February 13

Bruce Eckel, Thinking in Patterns with Java, cf. José Valente de Oliveira 10-1

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

From last week. Lecture 5. Outline. Principles of programming languages

Running Time. Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Project 2.5 Improved Euler Implementation

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies. Limitations of Experiments

Analysis of Algorithms

The golden search method: Question 1

Lecture 1: Introduction and Strassen s Algorithm

Computers and Scientific Thinking

Data Structures and Algorithms. Analysis of Algorithms

COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

Streams. Overview. The notion of stream Java I/O streamhierarchy Files, and file access using streams Serialization Sockets

Exercise Set: Implementing an Object-Oriented Design

MOTIF XF Extension Owner s Manual

CS211 Fall 2003 Prelim 2 Solutions and Grading Guide

n Some thoughts on software development n The idea of a calculator n Using a grammar n Expression evaluation n Program organization n Analysis

COSC 1P03. Ch 7 Recursion. Introduction to Data Structures 8.1

arxiv: v2 [cs.ds] 24 Mar 2018

Solution printed. Do not start the test until instructed to do so! CS 2604 Data Structures Midterm Spring, Instructions:

IMP: Superposer Integrated Morphometrics Package Superposition Tool

. Written in factored form it is easy to see that the roots are 2, 2, i,

Lecture 9: Exam I Review

Today s objectives. CSE401: Introduction to Compiler Construction. What is a compiler? Administrative Details. Why study compilers?

condition w i B i S maximum u i

n The C++ template facility provides the ability to define n A generic facility allows code to be written once then

Programming with Shared Memory PART II. HPC Spring 2017 Prof. Robert van Engelen

Chapter 5. Functions for All Subtasks. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Pattern Recognition Systems Lab 1 Least Mean Squares

Last class. n Scheme. n Equality testing. n eq? vs. equal? n Higher-order functions. n map, foldr, foldl. n Tail recursion

Lecture Notes 6 Introduction to algorithm analysis CSS 501 Data Structures and Object-Oriented Programming

CIS 121. Introduction to Trees

Chapter 3. More Flow of Control. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Algorithms and Data Structures

SECURITY PROOF FOR SHENGBAO WANG S IDENTITY-BASED ENCRYPTION SCHEME

! Given the following Structure: ! We can define a pointer to a structure. ! Now studentptr points to the s1 structure.

Abstract. Chapter 4 Computation. Overview 8/13/18. Bjarne Stroustrup Note:

Recursion. Recursion. Mathematical induction: example. Recursion. The sum of the first n odd numbers is n 2 : Informal proof: Principle:

What are we going to learn? CSC Data Structures Analysis of Algorithms. Overview. Algorithm, and Inputs

Package RcppRoll. December 22, 2014

Chapter 2. C++ Basics. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Alpha Individual Solutions MAΘ National Convention 2013

CS 111: Program Design I Lecture 19: Networks, the Web, and getting text from the Web in Python

Evaluation scheme for Tracking in AMI

top() Applications of Stacks

Numerical Methods Lecture 6 - Curve Fitting Techniques

Linked Lists 11/16/18. Preliminaries. Java References. Objects and references. Self references. Linking self-referential nodes

The Implementation of Data Structures in Version 5 of Icon* Ralph E. Gr is wo Id TR 85-8

Structuring Redundancy for Fault Tolerance. CSE 598D: Fault Tolerant Software

Elementary Educational Computer

The isoperimetric problem on the hypercube

Topics. Instance object. Instance object. Fundamentals of OT. Object notation. How do objects collaborate? Pearson Education 2007 Appendix (RASD 3/e)

1. (a) Write a C program to display the texts Hello, World! on the screen. (2 points)

CSC 220: Computer Organization Unit 11 Basic Computer Organization and Design

Fundamentals of Media Processing. Shin'ichi Satoh Kazuya Kodama Hiroshi Mo Duy-Dinh Le

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

CS200: Hash Tables. Prichard Ch CS200 - Hash Tables 1

9.1. Sequences and Series. Sequences. What you should learn. Why you should learn it. Definition of Sequence

The Magma Database file formats

Analysis of Algorithms

Solutions to Final COMS W4115 Programming Languages and Translators Monday, May 4, :10-5:25pm, 309 Havemeyer

n n B. How many subsets of C are there of cardinality n. We are selecting elements for such a

CS : Data Structures Michael Schatz. Sept Lecture 6. Introduction to Complexity

Basic allocator mechanisms The course that gives CMU its Zip! Memory Management II: Dynamic Storage Allocation Mar 6, 2000.

Package popkorn. R topics documented: February 20, Type Package

Last Class. Announcements. Lecture Outline. Types. Structural Equivalence. Type Equivalence. Read: Scott, Chapters 7 and 8. T2 y; x = y; n Types

CS : Programming for Non-Majors, Summer 2007 Programming Project #3: Two Little Calculations Due by 12:00pm (noon) Wednesday June

BaanERP Tools. Programming features

Lecture 5: Recursion. Recursion Overview. Recursion is a powerful technique for specifying funclons, sets, and programs

Python Programming: An Introduction to Computer Science

PLEASURE TEST SERIES (XI) - 04 By O.P. Gupta (For stuffs on Math, click at theopgupta.com)

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

CSE 417: Algorithms and Computational Complexity

CIS 121 Data Structures and Algorithms with Java Spring Stacks, Queues, and Heaps Monday, February 18 / Tuesday, February 19

CIS 121 Data Structures and Algorithms with Java Fall Big-Oh Notation Tuesday, September 5 (Make-up Friday, September 8)

Transcription:

Classes ad Objects jvo@ualg.pt José Valete de Oliveira 4-1 Agai: Distace betwee poits withi the first quadrat Sample iput Sample output 1 1 3 4 2 jvo@ualg.pt José Valete de Oliveira 4-2 1

The simplest class implemetatio /** @versio 0.0 */ // Bad code! WHY? class Poit { it x, y; double dist(poit p) { jvo@ualg.pt José Valete de Oliveira 3-3 Cotrol of visibility /** @versio 1.0 */ class Poit { private it x, y; public double dist(poit p) { Three keywords: - public - private - protected jvo@ualg.pt José Valete de Oliveira 3-4 2

Sitaxe jvo@ualg.pt José Valete de Oliveira 3-5 Sitaxe jvo@ualg.pt José Valete de Oliveira 3-6 3

Sitaxe for attributes jvo@ualg.pt José Valete de Oliveira 3-7 Sitaxe for attributes, illustrated /** @versio 1.0 */ class Poit { private it x, y; public double dist(poit p) { jvo@ualg.pt José Valete de Oliveira 3-8 4

Sitaxe for methods jvo@ualg.pt José Valete de Oliveira 3-9 Sitaxe for methods, illustrated @versio 1.0 class Poit { private it x, y; public double dist(poit p) { it dx = x p.getx(); it dy = y p.gety(); retur Math.sqrt(dx*dx+dy*dy); //. jvo@ualg.pt José Valete de Oliveira 3-10 5

A cliet of Poit public class Mai { public static void mai(strig[] args) { Scaer sc = ew Scaer (System.i); Poit A = ew Poit(sc.extIt(), sc.extit()); Poit B = ew Poit(sc.extIt(), sc.extit()); System.out.pritl( (it) A.dist(B) ); sc.close(); jvo@ualg.pt José Valete de Oliveira 3-11 Agai: a very bad solutio a la C // A very poor solutio, usefull for motivatio oly public class Bad { public static void mai (Strig [] args) { it xa, ya, xb, yb; Scaer sc = ew Scaer (System.i); xa = sc.extit(); //... Other vars readig omitted for brevity xa = -5; // Clear violatio ad o easy way to cotrol it L System.out.prit ( (it) dist(xa, ya, xb, yb) ); jvo@ualg.pt José Valete de Oliveira 3-12 6

A cliet of Poit public class Mai { public static void mai(strig[] args) { Scaer sc = ew Scaer (System.i); // Violatio Poit A = ew Poit(-5, sc.extit()); // easily detectable here! Poit B = ew Poit(sc.extIt(), sc.extit()); System.out.pritl( (it) A.dist(B) ); jvo@ualg.pt José Valete de Oliveira 3-13 Costructors class Perso { private Strig ame; public Perso(Strig s) { ame = s; class X { public X() { class Poit { private it x, y; public Poit(it x, it y) { setx(x); sety(y); 7

Costructors class Poit { private it x, y; public Poit(it x, it y) { setx(x); sety(y); A costructor: - iitializes a object -Reserves memory to object data (istace variables) -Returs a referece to that memory area // Cliet code Poit p; // variable declaratio p = ew Poit(1, 2); // calls the costructor Costructor A costructor is called wheever a object is created usig the keyword ew A costructor has the followig characteristics: - It has the same ame as the class - It does ot have a retur type (ot eve void!) // Cliet code Poit p; // variable declaratio p = ew Poit(1, 2); // calls the costructor 8

Default costructor If the class does ot defie ay costructor, the compiler will provide a default (or oargumet) costructor. Default costructor allows for istace variable default iitializatio If the class defie a cotructor (ay costructor) the compiler will ot provide a default costructor aymore. Default variable iitializatios Local variables are ot automatically iitialized Istace variables are automatically iitialized: q boolea types are iitialized to false q Other primitives are iitialized to the zero of their type q Class types are iitialized to ull It is a good programmig practice to explicitly iitialize istace variables withi a costructor 9

Default costructor example // AVOID: Used for motivatio oly class Poit { private it x, y=1024; public it getx() {retur x; public it gety() {retur y; public class Mai { public static void mai(strig[] args) { Poit p = ew Poit(); System.out.pritl(p.getX()); System.out.pritl(p.getY()); Default costructor example /** @versio 1.0 */ class Poit { private it pix, piy; public Poit(it x, it y) { setx(x); sety(y); public it getx() { retur pix; public it gety() { retur piy; public void setx(it x) { if (x<0) System.exit(1); pix = x; public void sety(it y) { Compile time error: o default costructor available! public class Mai { public static void mai(strig[] args) { Poit p = ew Poit(); System.out.pritl(p.getX()); System.out.pritl(p.getY()); 10

Explicit default costructor /** @versio 1.1 */ class Poit { private it pix, piy; public Poit() {; public Poit(it x, it y) { setx(x); sety(y); // Explicit default costructor a improved versio /** @versio 2.0 */ class Poit { private it pix, piy; public Poit() { pix = 0; piy = 0; public Poit(it x, it y) { setx(x); sety(y); // 11

Refereces I Java a variable cotais either a value of primitive data type or a referece. For primitive data types, assigig meas copyig the value resultig from the right expressio to the cotets of the variable o the left. I the example, it i, j =10; i=j; both i ad j have idepedet storage spaces, that after assigmet will have the same value jvo@ualg.pt José Valete de Oliveira 3-23 Refereces Should a variable hold a referece, assigig meas that the variable o the left will ow refer to the object resultig from the evaluatio of right expressio. I the example: Poit a, b = ew Poit(1, 2); a = b; a.setx(0); System.out.pritl(b.getX()); Both variables a, ad b will refer both to the same object of the class Poit jvo@ualg.pt José Valete de Oliveira 3-24 12

Argumet passig I Java, argumet passig is allways doe by value. The values of primitive data types are copied to the fuctio formal parameters; for other types, what are copied are the refereces (ot the objects themselves). This is equivalet to referece argumet passig. jvo@ualg.pt José Valete de Oliveira 3-25 Check poit: what s the output? class Poit { private it x,y; public void setx(it x) { x = x; public it getx() { retur x; public class Check{ public static void mai(strig[] args) { Poit origi = ew Poit(); Poit B = origi; B.setX(1); System.out.pritl(origi.getX()); jvo@ualg.pt José Valete de Oliveira 3-26 13

Method overloadig Method overloadig occurs whe two or more methods withi the same class have the same ame To be valid, ay two defiitios of the method ame must have differet sigatures q A sigature cosists of the ame of a method together with its parameterlist q Differig sigatures must have differet umber ad/or types of parameters Method overloadig Whe a ame of a method is declared twice withi the same class, the compiler views the secod declaratio as follows: - If the retur type ad the sigature of both methods agree, methods are viewedas a duplicate; it mult (it a, float b) { ; It mult (it a, floatb) { // ; //Error duplicate method - If the sigature of both methods are equal but the retur type are differet, the secod declaratio is viewed as a error; float mult (it a, float b) { // ; It mult (it a, float b) { ; //Error - If sigatures are differet i the umber ad/or type of parameters, both methods are viewed as overloaded. float mult (it a, float b) { // ; float mult ( float a, float b) { // ; //OK 14

Scope Each program elemet has a scope the cotext where it ca be referred to usig its simple ame. Elemets ca have the same ame whe their scope does ot overlap. { it k = 0; //... for (it k = 0; k< 3; k++) { // OK! No problem! Scope Each program elemet has a scope the cotext where it ca be referred to usig its simple ame. If the scopes of two variables overlap, the variable defied i the ier scope takes precedece over the variable with the same ame i the outer scope. { it k = 0; //... for (it k = 0; k< 3; k++) { // loop k hides outer k 15

Scope The Scope of a elemet is determied by the place where the elemet is defied. Variables with the same ame but differet scope are differet variables. Possible scopes i Java: q Local q Fuctio q File q Class q Prototype q Package class Poit { private it x, y; public Poit(it x, it y) { // x, y: the same ame // i a differet scope // Where are we so far? Java q q q q q A little bit of history Goals ad characteristics First programs Cotrol of visibility Classes Sitaxe Iitializatio of objects: costructors Refereces Method overloadig (to be cotiued.) jvo@ualg.pt José Valete de Oliveira 3-32 16