An introduction to Java II

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

Interfaces Java. Overview. n Java interfaces. q Introduction. q Sintaxe. q UML notation. q Multi-inheritance of interfaces

From UML to Java and return (object-oriented modeling II)

Java Classes & Primitive Types

Java Classes & Primitive Types

w3.ualg.pt/~jvo/poo

VARIABLES AND TYPES CITS1001

Programming Languages and Techniques (CIS120)

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

Lecture 12: Classes II

Abstract Data Types (ADT) and C++ Classes

Lecture 3. Lecture

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

Container Vs. Definition Classes. Container Class

Java Fundamentals (II)

Introduction to Programming Using Java (98-388)

Class, Variable, Constructor, Object, Method Questions

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.

Chapter 4 Defining Classes I

Programming, numerics and optimization

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

STUDENT LESSON A5 Designing and Using Classes

index.pdf January 21,

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Programming Languages and Techniques (CIS120)

ITI Introduction to Computing II

Lecture 5: Methods CS2301

ITI Introduction to Computing II

3.1 Class Declaration

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Industrial Programming

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes

JCF: user defined collections

ITI Introduction to Computing II

Object Oriented Programming

CS170 Introduction to Computer Science Midterm 2

Selected Questions from by Nageshwara Rao

Array. Prepared By - Rifat Shahriyar

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Creating an object Instance variables

1B1b. Classes in Java Part III. Review. Static. Static (2) Example. Static (3) 1B1b Lecture Slides. Copyright 2004, Graham Roberts 1

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

Object Oriented Modeling

Object Oriented Programming

Programming Languages and Techniques (CIS120)

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

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

APCS Semester #1 Final Exam Practice Problems

Object-Oriented Programming (Java)

Problem Grade Total

( &% class MyClass { }

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.


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

Conversions and Overloading : Overloading

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

C++ (classes) Hwansoo Han

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CSC Java Programming, Fall Java Data Types and Control Constructs

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

Derived and abstract data types. TDT4205 Lecture 15

(3) Some memory that holds a value of a given type. (8) The basic unit of addressing in most computers.

Software Design and Analysis for Engineers

Object-Oriented Programming Concepts

Introduction to Software Development (ISD) Week 3

CS 231 Data Structures and Algorithms, Fall 2016

Building Java Programs

Imperative Languages!

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

The return Statement

Java Identifiers, Data Types & Variables

Use the scantron sheet to enter the answer to questions (pages 1-6)

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

CSEN401 Computer Programming Lab. Topics: Introduction and Motivation Recap: Objects and Classes

More Java Basics. class Vector { Object[] myarray;... //insert x in the array void insert(object x) {...} Then we can use Vector to hold any objects.

Recitation 3 Class and Objects

PIC 10A. Lecture 15: User Defined Classes

Getting started with Java

CS260 Intro to Java & Android 03.Java Language Basics

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

Object Oriented Programming

Lecture 7 Objects and Classes

For this section, we will implement a class with only non-static features, that represents a rectangle

What will this print?

The Java Programming Language

Fundamentals of Programming Data Types & Methods

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Objects and Classes -- Introduction

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

CS 101 Fall 2006 Midterm 3 Name: ID:

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

Programming Languages and Techniques (CIS120)

Programming Language Concepts: Lecture 2

int[] a; a = new int[8]; a[0] = 1; a[1] = 1; for (int i = 2; i < 8; i++) a[i] = a[i-1] - a[i-2];

Constants, References

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

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

Chapter 11: Creating Classes

Transcription:

An introduction to Java II Bruce Eckel, Thinking in Java, 4th edition, PrenticeHall, New Jersey, cf. http://mindview.net/books/tij4 jvo@ualg.pt José Valente de Oliveira 4-1 Java: Generalities A little bit of History Goals and characteristics First programs jvo@ualg.pt José Valente de Oliveira 3-2 1

Classes and objects Bruce Eckel, Thinking in Java, 4th edition, PrenticeHall, New Jersey, cf. http://mindview.net/books/tij4 jvo@ualg.pt José Valente de Oliveira 4-3 Recall: What s an object? An object is like a black box: Internal details are hidden. An object represents a concrete entity of the problem domain, that handles a specific task Examples include: Tangible things as cars, bank accounts Roles as employee, boss,... Interactions as contract, sale,... jvo@ualg.pt José Valente de Oliveira 4-4 2

Problem: Distance between points within the first quadrant Sample input Sample output 1 1 3 4 2 jvo@ualg.pt José Valente de Oliveira 4-5 Problem: Distance between points within the first quadrant Write a program that, given any two points with non-negative coordinates,compute the integer part of the distance between then Let the coordenates of points A, and B be (xa, ya) e (xb, yb) respectively, the distance d between A and B is given by: 2 2 d = ( xa xb ) + ( ya yb ) Input Input has two rows. The first has two integers XA, YA, representing the coordinates of point A. The second line is similar to the first one,representing the coordinates of point B. 0 <= XA <= 1000, 0 <= YA <= 1000 Output The output is an integer denoting the integer part of the distance between the input points Sample input Sample output 1 1 3 4 2 jvo@ualg.pt José Valente de Oliveira 4-6 3

Objects: a definition, again An object can be seen as an abstraction which represents an entity with interest for the problem to solve. An object has: State Behaviour Identity jvo@ualg.pt José Valente de Oliveira 4-7 Objects: a definition, again An object can be seen as an abstraction which represents an entity with interest for the problem to solve. An object has: State Behaviour Identity Point A is an object with: -State: Coordinates (X A =1, Y A =1) - Behaviour: computes the distance between itself and another point - Identify: Object point A is diferent from any other object jvo@ualg.pt José Valente de Oliveira 4-8 4

What s a class? A class can be seen as a description of a set of objects sharing the same data structure (not the same data) and the same behaviour (functions) jvo@ualg.pt José Valente de Oliveira 4-9 Examples of classes and their objects Class Objects Data Typical functions Point (0, 0) (4.5; 7.2) x=0; y =0 x=4,5; y=7.2 BankAccount account1 Balance=0 Number=12 Fraction ½ Numerator = 1 Denominator =2 dist Transfer withdraw sum jvo@ualg.pt José Valente de Oliveira 4-10 5

The simplest class implementation /** @version 0.0 */ // Bad code usefull for motivation only int x, y; double dist(point p) { jvo@ualg.pt José Valente de Oliveira 3-11 Control of visibility /** @version 1.0 */ private int x, y; public double dist(point p) { Three keywords: - public - private - protected jvo@ualg.pt José Valente de Oliveira 3-12 6

Sintaxe jvo@ualg.pt José Valente de Oliveira 3-13 Sintaxe jvo@ualg.pt José Valente de Oliveira 3-14 7

Sintaxe for attributes jvo@ualg.pt José Valente de Oliveira 3-15 Sintaxe for attributes, illustrated /** @version 1.0 */ private int x, y; public double dist(point p) { jvo@ualg.pt José Valente de Oliveira 3-16 8

Sintaxe for methods jvo@ualg.pt José Valente de Oliveira 3-17 Sintaxe for methods, illustrated @version 1.0 private int x, y; public double dist(point p) { int dx; dx = x p.getx(); int dy = y p.gety(); return Math.sqrt(dx*dx+dy*dy); jvo@ualg.pt José Valente de Oliveira 3-18 9

Constructors jvo@ualg.pt José Valente de Oliveira 4-19 Check point: what s common in these classes? class Person { private String name; public Person(String s) { name = s; class X { public X() { private int x, y; public Point(int x, int y) { setx(x); sety(y); 10

Constructors private int x, y; public Point(int x, int y) { setx(x); sety(y); Constructors initializes an object - Reserve memory to object data (instance variables) - Return a reference to that memory area // Client code Point p; // variable declaration p = new Point(1, 2); // calls the constructor Constructor A constructor is called whenever a object is created, using the keyword new A constructor has the following characteristics: - It has the same name as the class - It does not have a return type (not even void!) // Client code Point p; // variable declaration p = new Point(1, 2); // calls the constructor 11

Default constructor If the class does not define any constructor, the compiler will provide a default (or nonargument) constructor. Default constructor allows for instance variable default initialization If the class define a contructor (any constructor) the compiler will not provide a default constructor. Default variable initializations Local variables are not automatically initialized Instance variables are automatically initialized: boolean types are initialized to false Other primitives are initialized to the zero of their type Class types are initialized to null It is a good programming practice to explicitly initialize instance variables within a constructor 12

Default constructor example // AVOID: Used for motivation only private int x, y=1024; public int getx() {return x; public int gety() {return y; public class Main { public static void main(string[] args) { Point p = new Point(); System.out.println(p.getX()); System.out.println(p.getY()); Default constructor example /** @version 1.0 */ private int _x_, _y_; public Point(int x, int y) { setx(x); sety(y); public int getx() { return _x_; public int gety() { return _y_; public void setx(int x) { if (x<0) System.exit(1); _x_ = x; public void sety(int y) { public class Main { public static void main(string[] args) { Point p = new Point(); System.out.println(p.getX()); System.out.println(p.getY()); 13

Explicit default constructor /** @version 1.1 */ private int _x_, _y_; public Point() { public Point(int x, int y) { setx(x); sety(y); // Explicit default constructor an improved version /** @version 2.0 */ private int _x_, _y_; public Point() { _x_ = 0; _y_ = 0; public Point(int x, int y) { setx(x); sety(y); // 14

References In Java a variable contains either a value of primitive data type or a reference. If the variable are primitive data types, assigning means copying the value resulting from the right expression to the contents of the variable on the left. In the example, int i, j =10; i=j; both i and j have independent storage spaces, that after assignment will have the same value jvo@ualg.pt José Valente de Oliveira 3-29 References Should a variable hold a reference, assigning means that the variable on the left will now refer to the object resulting from the evaluation of right expression. In the example: Point a, b = new Point(1, 2); a=b; a.setx(0); System.out.println(b.getX()); Both variables a, andb willreferbothtothesame object of the class Point jvo@ualg.pt José Valente de Oliveira 3-30 15

Argument passing In Java argument passing is allways done by value. The values of primitive data types are copied to the function formal parameters; for other types, what are copied are the references (not the objects themselves). This is equivalent to reference argument passing. jvo@ualg.pt José Valente de Oliveira 3-31 Method overloading Method overloading occurs when two or more methods within the same class have the same name To be valid, any two definitions of the method name must have different signatures A signature consists of the name of a method together with its parameter list Differing signatures must have different number and/or types of parameters 16

Method overloading When a name of a method is declared twice within the same class, the compiler views the second declaration as follows: - If the return type and the signature of both methods agree, methods are viewed as a duplicate; int mult (int a, float b) { // ; Int mult (int a, float b) { // ; //Error duplicate method - If the signature of both methods are equal but the return type are different, the second declaration is viewed as an error; float mult (int a, float b) { // ; Int mult (int a, float b) { // ; //Error - If signatures are different in the number and/or type of parameters, both methods are viewed as overloaded. float mult (int a, float b) { // ; float mult ( float a, float b) { // ; //OK Check point: what s the output? private int x,y; public void setx(int nx) { x = nx; public int getx() { return x; public class Check{ public static void main(string[] args) { Point origin = new Point(); Point B = origin; B.setX(1); System.out.println(origin.getX()); jvo@ualg.pt José Valente de Oliveira 3-34 17

Where are we so far? Java A little bit of history Goals and characteristics First programs Control of visibility Classes Sintaxe Initialization of objects: constructors References Method overloading (to be continued.) jvo@ualg.pt José Valente de Oliveira 3-35 18