Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

Similar documents
Chapter 4. Defining Classes I

Chapter 4. Defining Classes I

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B

Comp 249 Programming Methodology

Comp 249 Programming Methodology Chapter 8 - Polymorphism

Copyright 2007 Pearson Addison-Wesley Copyright 2018 Aiman Hanna All rights reserved

Comp 249 Programming Methodology Chapter 9 Exception Handling

Comp 249 Programming Methodology

Chapter 4 Defining Classes I

Methods and Data (Savitch, Chapter 5)

Copyright 2007 Pearson Addison-Wesley Copyright 2019 Aiman Hanna All rights reserved

Introduction to Programming Using Java (98-388)

Comp 249 Programming Methodology Chapter 11 Recursion

Defining Classes and Methods

Ticket Machine Project(s)

CHAPTER 7 OBJECTS AND CLASSES

EECS168 Exam 3 Review

This exam is open book. Each question is worth 3 points.

Anatomy of a Class Encapsulation Anatomy of a Method

CHAPTER 7 OBJECTS AND CLASSES

Objectives. Defining Classes and Methods. Objectives. Class and Method Definitions: Outline 7/13/09

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

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

COMP 250 Winter 2011 Reading: Java background January 5, 2011

Methods. Methods. Mysteries Revealed

5/24/12. Introduction to Polymorphism. Chapter 8. Late Binding. Introduction to Polymorphism. Late Binding. Polymorphism and Abstract Classes

5. Defining Classes and Methods

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

5. Defining Classes and Methods

Defining Classes and Methods

Object-Oriented Programming in Java

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CS313D: ADVANCED PROGRAMMING LANGUAGE

Introduction to Programming (Java) 4/12

Chapter 6 Introduction to Defining Classes

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 5. Defining Classes II. Slides prepared by Rose Williams, Binghamton University

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

ECE 122. Engineering Problem Solving with Java

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.

Defining Classes and Methods

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Java Identifiers, Data Types & Variables

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

More About Objects and Methods

More About Objects and Methods. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Chapter 4: Writing Classes

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

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

Array. Prepared By - Rifat Shahriyar

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

Defining Classes and Methods

Understanding class definitions

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

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

CS162: Introduction to Computer Science II. Primitive Types. Primitive types. Operations on primitive types. Limitations

Lecture Set 4: More About Methods and More About Operators

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

Assignment 1 due Monday at 11:59pm

// constructor: takes a String as parameter and creates a public Cat (String x) { name = x; age = 0; lives = 9; // cats start out with 9 lives }

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

PROGRAMMING FUNDAMENTALS

Object Oriented Programming SCJ2153. Class and Object. Associate Prof. Dr. Norazah Yusof

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Defining Classes I. 4.1 Class Definitions Information Hiding and Encapsulation Overloading

APCS Semester #1 Final Exam Practice Problems

Arrays Classes & Methods, Inheritance

CS 101 Fall 2006 Midterm 3 Name: ID:

Lecture 13 & 14. Single Dimensional Arrays. Dr. Martin O Connor CA166

Understanding class definitions. Looking inside classes (based on lecture slides by Barnes and Kölling)

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

Module 5. Arrays. Adapted from Absolute Java, Rose Williams, Binghamton University

McGill University School of Computer Science COMP-202A Introduction to Computing 1

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

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

MIDTERM REVIEW. midterminformation.htm

Lecture 3. Lecture

CS1083 Week 2: Arrays, ArrayList

OBJECTS AND CLASSES CHAPTER. Final Draft 10/30/2011. Slides by Donald W. Smith TechNeTrain.com

Where do objects come from? Good question!

CS162: Introduction to Computer Science II

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Lecture Set 4: More About Methods and More About Operators

Lecture 10 Declarations and Scope

Pace University. Fundamental Concepts of CS121 1

Lab5. Wooseok Kim

Java Classes & Primitive Types

Today s Agenda. Quick Review

Java Classes & Primitive Types

CSE 8B Intro to CS: Java

Lecture 8 Classes and Objects Part 2. MIT AITI June 15th, 2005

Recitation 02/02/07 Defining Classes and Methods. Chapter 4

More About Objects and Methods. Objectives. Outline. Chapter 6

Transcription:

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by Pearson Education / Addison-Wesley. Copyright 2007 Pearson Addison-Wesley Copyright 2008-2016 Aiman Hanna All rights reserved

Class Definitions We have already been using some of the predefined classes, i.e. String and Scanner classes We can add/define our own classes to the language A class determines: 1) Attributes, or Instance Variables: the types of data that an object can contain, 2) Methods: the actions it can perform Once a new class is defined, objects, or instances, can be created from this class 4-2

Class Definitions int x, y; char ch; Data declarations Method declarations 4-3

The new Operator An object of a class is named or declared by a variable of the class type: ClassName objectname; The new operator must then be used to create the object and associate it with its variable name (however, some few exceptions do exist): objectname = new ClassName(); These can be combined as follows: ClassName objectname = new ClassName(); Example: Car c1 = new Car(); // Car is the class name and // c1 is the object name // IMPORTANT NOTE: In fact, // c1 is a pointer/reference // to the object 4-4

Instance Variables and Methods Instance variables (attributes) can be defined as in the following two examples Note the public modifier (for now): public int numberofdoors; public double Price; In order to refer to a particular instance variable, preface it with its object name as follows: c1.price c2.price c1.numberofdoors c1 & c2 are just two objects from the class 4-5

Instance Variables and Methods Method definitions are divided into two parts: a heading and a method body: public void mymethod() { code to perform some action and/or compute a value } // Heading // Body Methods are invoked using the name of the calling object and the method name as follows: objname.methodname(); Example: C1.getNumberOfDoors(); Invoking a method is equivalent to executing the method body 4-6

File Names and Locations Reminder: a Java file must be given the same name as the class it contains with an added.java at the end For example, a class named Car must be in a file named Car.java For now, your program and all the classes it uses should be in the same directory or folder 4-7

More About Methods There are two kinds of methods: Methods that compute/perform an action then return a value Methods that compute/perform an action then does not return a value This type of method is called a void method; in other words, it returns void Notice that in both cases, the function do indeed perform an action 4-8

More About Methods A method that returns a value must specify the type of that value in its heading: public typereturned methodname(paramlist) Note: paramlist is optional Examples: public double getprice(); public int getnumofdoors(); public void setnumofdoors(int nd); // nd is just // a name 4-9

main is a void Method A program in Java is just a class that has a main method When you give a command to run a Java program, the run-time system invokes the method main Note that main is a void method, as indicated by its heading: public static void main(string[] args) 4-10

return Statements The body of both types of methods contains a list of declarations and statements enclosed in a pair of braces public <void or typereturned> mymethod() { } declarations statements Body 4-11

return Statements The body of a method that returns a value must also contain one or more return statements A return statement specifies the value returned and ends the method invocation: return Expression; Expression can be any expression that evaluates to something of the type returned listed in the method heading 4-12

return Statements A void method need not contain a return statement, unless there is a situation that requires the method to end before all its code is executed In this context, since it does not return a value, a return statement is used without an expression: return; 4-13

Method Definitions An invocation of a method that returns a value can be used as an expression anyplace that a value of the returned type can be used: double pr; pr = c1.getprice(); An invocation of a void method is simply a statement: objectname.methodname(); Examples: c1.setprice(20000); c1.showmodel(); VehicleSearch1.java (MS-Word file) 4-14

Example: The Vehicle Class See VehicleSearch1.java class Vehicle int numofdoors; double price; int maxspeed; v1 numofdoors 4 price 10000 maxspeed 280 v2 numofdoors 4 price 10000 maxspeed 280 v3 numofdoors 4 price 10000 maxspeed 280 v1, v2 & v3 upon creation 4-15

Constructors A constructor is a special kind of method that is designed to initialize the instance variables for an object: public ClassName(anyParameters){code} A constructor must have the same name as the class A constructor has no type returned, not even void VehicleSearch2.java (MS-Word file) 4-16

public and private Modifiers The modifier public means that there are no restrictions on where an instance variable or method can be used The modifier private means that an instance variable or method cannot be accessed by name outside of the class VehicleSearch3.java (MS-Word file) VehicleSearch4.java (MS-Word file) 4-17

Include a No-Argument Constructor You should include a default, or no-argument constructor as part of your program. Default constructors will be discussed later in full details. If you do not include any constructors in your class, Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created If you include even one constructor (possibly non-default) in your class, Java will not provide this default constructor 4-18

Local Variables A variable declared within a method definition is called a local variable All variables declared in the main method are local variables All method parameters are local variables If two methods each have a local variable of the same name, they are still two entirely different variables 4-19

Global Variables Some programming languages include another kind of variable called a global variable The Java language does not have global variables 4-20

Blocks A block is another name for a compound statement, that is, a set of Java statements enclosed in braces,{} A variable declared within a block is local to that block, and cannot be used outside the block Once a variable has been declared within a block, its name cannot be used for anything else within the same method definition 4-21

Declaring Variables in a for Statement You can declare one or more variables within the initialization portion of a for statement A variable so declared will be local to the for loop, and cannot be used outside of the loop If you need to use such a variable outside of a loop, then declare it outside the loop Statements14.java (MS-Word file) Statements15.java (MS-Word file) 4-22

Parameters of a Primitive Type A method can accept no parameters, one parameter, or few of them (parameter list) These parameter(s) are referred to as formal parameters public void setvehicleinfo(int nd, double pr, int mxsp) When a method is invoked, the appropriate values must be passed to the method in the form of arguments, and must be in the right order These arguments are called actual parameters c1.setvehicleinfo(4, 12500.99, 280); 4-23

Parameters of a Primitive Type The type of each argument must be compatible with the type of the corresponding parameter. The following two statements use the method correctly c1.setvehicleinfo(4, 12500.99, 280); int n = 5, m = 260; double p = 19700.95; c1.setvehicleinfo(n, p, m); NOTE: In both examples, the value of each argument (not the variable name) is the one plugged into the corresponding method parameter This method of plugging in arguments for formal parameters is known as the call-by-value mechanism MethodParameters1.java (MS-Word file) 4-24

Parameters of a Primitive Type If argument and parameter types do not match exactly, Java will attempt to make an automatic type conversion A primitive argument can be automatically type cast from any of the following types, to any of the types that appear to its right: byte short int long float double char 4-25

Methods That Return a Boolean Value An invocation of a method that returns a value of type boolean returns either true or false Therefore, it is common practice to use an invocation of such a method to control statements and loops where a boolean expression is expected i.e. within if-else statements, while loops, etc. 4-26

Comparing Objects of the Same Class for Equality You cannot use == to compare objects VehicleCompare1.java (MS-Word file) Instead use methods such as user-defined equals, or tostring to compare the objects VehicleCompare2.java (MS-Word file) VehicleCompare3.java (MS-Word file) VehicleCompare4.java (MS-Word file) 4-27

Accessor and Mutator Methods Accessor methods allow the programmer to obtain the value of an object's instance variables The data can be accessed but not changed The name of an accessor method typically starts with the word get Mutator methods allow the programmer to change the value of an object's instance variables in a controlled manner Incoming data is typically tested and/or filtered The name of a mutator method typically starts with the word set 4-28

Encapsulation 4-29

A Class Has Access to Private Members of All Objects of the Class Within the definition of a class, private members of any object of the class can be accessed, not just private members of the calling object For example, see the equals function in VehicleCompare2.java (MS-Word file) The function has access to the private date of the passed object, vec 4-30