COMP-202: Foundations of Programming. Lecture 10: Method Overloading and Passing Objects to Methods. Sandeep Manjanna, Summer 2015

Similar documents
COMP-202: Foundations of Programming. Lecture 16: Reference types Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 11: ArrayList, and Linked List Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

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

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)

COMP-202: Foundations of Programming. Lecture 9: Classes and Objects Sandeep Manjanna, Summer 2015

CSE 11 Midterm Fall 2008

COMP-202: Foundations of Programming. Lecture 5: Arrays, Reference Type, and Methods Sandeep Manjanna, Summer 2015

Selected Questions from by Nageshwara Rao

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

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

CS 101 Spring 2006 Final Exam Name: ID:

index.pdf January 21,

Object Orientated Programming Details COMP360

ITI Introduction to Computing II

ITI Introduction to Computing II

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

Java Foundations Certified Junior Associate

Zheng-Liang Lu Java Programming 45 / 79

Objects as a programming concept

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

Practice Midterm 1. Problem Points Score TOTAL 50

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

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

( &% class MyClass { }

Lecture Set 4: More About Methods and More About Operators

Java Basic Programming Constructs

Conversions and Overloading : Overloading

Chapter 6 Classes and Objects

1 If you want to store a letter grade (like a course grade) which variable type would you use? a. int b. String c. char d. boolean

Computer Science is...

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects

Fundamentals of Programming Data Types & Methods

CMSC 132: Object-Oriented Programming II. Inheritance

BM214E Object Oriented Programming Lecture 8

CSCI 136 Written Exam #0 Fundamentals of Computer Science II Spring 2015

Introduction to Programming Using Java (98-388)

Lecture 3. Lecture

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016

What will this print?

Lecture Set 4: More About Methods and More About Operators

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit.

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

Questions Answer Key Questions Answer Key Questions Answer Key

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

Chapter 8 Objects and Classes Dr. Essam Halim Date: Page 1

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

1.00 Introduction to Computers and Engineering Problem Solving Quiz 1 March 4, 2005

CS Week 13. Jim Williams, PhD

Chapters 1-4 Summary. Syntax - Java or C? Syntax - Java or C?

CS 101 Fall 2006 Midterm 1 Name: ID:

Practice Midterm 1 Answer Key

CS171:Introduction to Computer Science II

In Java there are three types of data values:

Introduction to Java

PROGRAMMING FUNDAMENTALS

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

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

1 Shyam sir JAVA Notes

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Control Structures in Java if-else and switch

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:

COE318 Lecture Notes Week 4 (Sept 26, 2011)

4 Programming Fundamentals. Introduction to Programming 1 1

CS 177 Week 15 Recitation Slides. Review

Object Oriented Programming in C#

CSE 113 A. Announcements - Lab

Lecture 6 Introduction to Objects and Classes

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

CS 1302 Chapter 9 (Review) Object & Classes

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

CSE 142, Summer 2015

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Inheritance and Polymorphism

BM214E Object Oriented Programming Lecture 4

CLASSES AND OBJECTS. Fundamentals of Computer Science I

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

BM214E Object Oriented Programming Lecture 7

CS171:Introduction to Computer Science II

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

CS1150 Principles of Computer Science Objects and Classes

Week 6 CS 302. Jim Williams, PhD

COE318 Lecture Notes Week 6 (Oct 10, 2011)

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

MIDTERM REVIEW. midterminformation.htm

CONDITIONAL EXECUTION

CS 302 Week 9. Jim Williams

Chapter 3 Classes. Activity The class as a file drawer of methods. Activity Referencing static methods

CS Week 5. Jim Williams, PhD

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

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

Transcription:

COMP-202: Foundations of Programming Lecture 10: Method Overloading and Passing Objects to Methods. Sandeep Manjanna, Summer 2015

Announcements Assignment 3: Due on 14 th of June at 11:30 pm. Midterm grades are published on MyCourses. Class Average is 75.55 %. Midterm exam is uploaded on the course website for your reference.

This Lecture Review on static, public and private access specifiers Method Overloading Passing objects to methods One step at a time.

Review: static, public, and private

What is the output? public class Bird { private double height; private double wingspan; private boolean canfly; public Bird (double h, double w, boolean f){ height = h; wingspan = w; canfly = f; public static void main(string [] args){ Bird b1 = new Bird(0.5, 1, true); System.out.println("The Bird data is : Height = "+b1.height+" Wing Span = "+b1.wingspan+" Can Fly? " +b1.canfly);

What is the output? public class Bird { private double height; private double wingspan; public Bird (double height, double wingspan){ height = height; wingspan = wingspan; public static void main(string [] args){ Bird b1 = new Bird(0.5, 1); Ambiguity with the variable names. Need to use this.height to refer to the variable height of the class Bird. System.out.println("The Bird data is : Height = "+b1.height+" Wing Span = "+b1.wingspan);

What is the output? public class Bird { private double height; private double wingspan; private boolean canfly; Static method cannot access non-static variable height. public Bird (double h, double w, boolean f){ height = h; wingspan = w; canfly = f; public static void main(string [] args){ System.out.println("The height is : "+ height);

What is the output? public class Bird { private double height; private double wingspan; private static int numbirds = 0; Static method can access static variable numbirds. So NO ERROR. public Bird (double h, double w){ height = h; wingspan = w; numbirds++; public static void main(string [] args){ System.out.println("The numbirds = "+ numbirds);

static Public Class Student { public int ID; public String Name; public String Grade; public static int numstudents = 0; numstudents static variable is shared by all the objects. 4 Objects : ID: Name: Grade: 435678271 Sarah A- ID: Name: Grade: 435645231 Bob B- ID: Name: Grade: 435932949 San F ID: Name: Grade: 435321234 Nat A

The variable height is private to the class its defined in (Bird). Cannot be accessed from other classes. public class Bird { private double height; private double wingspan; private static int numbirds = 0; public Bird (double h, double w){ height = h; wingspan = w; numbirds++; public class testbird{ public static void main(string[] str){ Bird b1 = new Bird(0.4,1.5); System.out.println("The Bird data is : Height = "+b1.height);

Changing height to public makes it accessible from outside classes. public class Bird { public double height; private double wingspan; private static int numbirds = 0; public Bird (double h, double w){ height = h; wingspan = w; numbirds++; public class testbird{ public static void main(string[] str){ Bird b1 = new Bird(0.4,1.5); System.out.println("The Bird data is : Height = "+b1.height);

Method Overloading

Same name, Different behavior CALL

Same name, Different behavior Compute Area Rectangle Area = l * b Circle Area = Triangle Area =

In Java We have already seen such behavior in Java!!! System.out.println(3); // int System.out.println('3'); // char System.out.println("3"); // String int[] intarr = {1, 2, 3; System.out.println(intarr); // prints memory address System.out.println(true); // boolean

Method Overloading You're allowed to have different methods with the same name, as long as they have different signatures. Signature = method name + parameter list (with types) So, as long as the methods require different parameter types, you're fine.

Okay: Examples public void dosomething(int val) { public void dosomething(int val, double val2) { public void dosomething(string val) { public void dosomething(double val, int val2) { Not okay (given above): Just having different returntypes does not qualify as different method signature. public String dosomething(int val) { public void dosomething(int otherval) {

Example public class overload{ public static void main(string [] str){ System.out.println("Area of this circle = "+computearea(5)); System.out.println("Area of this circle = "+computearea(5,3)); public static double computearea(double r){ return Math.PI*r*r; public static double computearea(double l, double b){ return l*b;

Bad Idea There's nothing to stop you from having an overloaded method, where each version does something completely unrelated. public void dosomething(int val) { System.out.println(val); public String dosomething(double val) { return "" + val;

Overloading the Constructor public class Employee { private int id; private String name; private double salary; public Employee() { System.out.println("In Constructor 1"); id = 0; name = " "; salary = 0; Contd.. public Employee(int x) { System.out.println("In Constructor 2"); id = x; public Employee(String str) { System.out.println("In Constructor 3"); name = str; public static void main(string [] str) { Employee e1 = new Employee(); Employee e2 = new Employee(101); Employee e3 = new Employee("Bob");

Let us Try it out!! Write a Cat class. It should: have two fields, for the name and the age have two possible constructors (overloaded). Both of them requires the name of the cat. One of them creates a kitten with default age 0.0; the other creates a cat of a specified age. have a meow() method. If the cat has age < 1.0, this method prints "<name> mews". Otherwise, it prints "<name> meows". a birthday() method that increments age by 1.0 Write code to test this class as well.

Objects Are Reference Types Primitive types: float, int, double, boolean, char, long, short, byte Variables of primitive types store the actual value Reference types: arrays, every other type Variables store an address to the actual value in memory.

Declaring Object Variables Variable declaration: Cat c1; No new Cat object is created. Only a place to store a memory address of a Cat object. c1 Can take the address of Cat object

Creating the Object in Memory This happens with the new keyword. Cat c1; c1 = new Cat ( Kitty"); Picture in your mind: @1100 @1100 c1.name Kitty".age 0.0

Variable Assignment Cat c1 = new Cat( Kitty"); Cat c2 = c1; @1100 @1100 c1 @1100.name Kitty".age 0.0 c2

Variable Assignment @1100 Cat c1 = new Cat( Kitty"); Cat c2 = c1; c2 = new Cat("Whiskers", 3.0); @1100 c1.name Kitty".age 0.0 @1500 @1500 @1100 c2.name "Whiskers".age 3.0

Variable Assignment Cat c1 = new Cat( Kitty"); Cat c2 = c1; c2 = new Cat("Whiskers", 3.0); c2 = c1; @1100 c1 @1100.name Kitty".age 0.0 @1500 @1500 @1100 c2 Nothing refers to Whiskers any more!.name "Whiskers".age 3.0

Garbage Collection At some point, Java will notice and will perform garbage collection to free up that memory. @1100 @1100 c1 @1100 c2.name Kitty".age 0.0

Aliases Can change an object from any of its references: c1.birthday(); (OR c2.birthday()); @1100 @1100 c1 @1100 c2.name Kitty".age 1.0 c1 and c2 are known as aliases of each other. They point to the same place in memory.

Comparisons Using == to compare reference types means you are comparing their memory addresses. You need to write your own.equals() method for a class if you want to compare their values. e.g., c1 == c2 true, because they point to the same place in memory If I create another Cat called Kitty" with the same age and put it into a variable called c3, c1 == c3 will be false

You can use null to mean that a reference type is referring to nothing. (This is sometimes useful.) c1 = null; null null @1100 c1 @1100.name Kitty".age 1.0 c2

Checking for null You can check if a reference type is pointing to nothing using ==. if (c1 == null) { c1 = new Cat("Paws", 0.6);

Passing Reference Types Recall: Parameter passing works just like an assignment statement. The value of the actual parameter (the value when calling the method) is copied into the method's formal parameter (the variable name in the method). This means when passing reference types, we are copying the address to the object.

Example public static void agecat(cat cat) { // this changes the value pointed to by cat cat.birthday(); In the main method: Cat c = new Cat("Harvey", 0.4); agecat(c); // Harvey is now 1.4 years old.

Example 2 public static void replacecat(cat cat) { cat = new Cat("AngryCat", 2.0); In the main method: Cat c = new Cat("Harvey", 0.4); replacecat(c); // c still points to Harvey

Try it out!! Write a.equals(cat) method for the Cat class that returns true if and only if both cats have the same name and age.

Try it out!! Write a CatRescue class: 1. Stores an array of Cats waiting to be adopted. 2. Takes an int in its constructor to represent the capacity of the cat rescue shelter. 3. Has an addcat(cat) method which adds a cat to the shelter (i.e., adds it to the next available spot in the array). Returns true if successful. If shelter is full, don't do anything and return false. 4. Has an adopt() method which returns the oldest cat in the shelter, removing it from the shelter.

Summary Method Overloading Objects are References Passing Objects into Methods