More Methods GEEN163

Similar documents
Using Classes. GEEN163 Introduction to Computer Programming

Loops. GEEN163 Introduction to Computer Programming

Using Classes. GEEN163 Introduction to Computer Programming

Decisions, Decisions, Decisions. GEEN163 Introduction to Computer Programming

Over and Over Again GEEN163

Review for the Third Exam COMP163

Methods & Classes COMP163

Bjarne Stroustrup. creator of C++

Assignment 1 due Monday at 11:59pm

Course Outline. Introduction to java

One Ring to rule them all, One Ring to bring them all,

Arrays Classes & Methods, Inheritance

CMP 326 Midterm Fall 2015

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I

1B1b Classes in Java Part I

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

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

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

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

Object Orientated Programming Details COMP360

The high-level language has a series of primitive (builtin) types that we use to signify what s in the memory

Recitation 3 Class and Objects

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Classes, Objects, and OOP in Java. June 16, 2017

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

(a) Write the signature (visibility, name, parameters, types) of the method(s) required

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

Building Java Programs

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

Exam Duration: 2hrs and 30min Software Design

2. [20] Suppose we start declaring a Rectangle class as follows:

Second Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 11 November 2010

AP CS Unit 8: Inheritance Exercises

Evaluating the Style of your programs

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

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

AP CS Unit 6: Inheritance Exercises

Programming Assignment 8 ( 100 Points )

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

( &% class MyClass { }

More about GUIs GEEN163

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

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

CS 1331 Exam 1 ANSWER KEY

COMP102: Test. 18 April, 2005

San Jose State University College of Science Department of Computer Science CS151, Object-Oriented Design, Sections 1, 2, and 3, Spring 2018

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

CS304 Object Oriented Programming Final Term

Notes on Chapter Three

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

Computer Science 1 Honors

Classes. Classes as Code Libraries. Classes as Data Structures. Classes/Objects/Interfaces (Savitch, Various Chapters)

AP Computer Science A Unit 2. Exercises

Array. Prepared By - Rifat Shahriyar

CSCI 1226 Sample Midterm Exam

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

Name: Checked: Access the Java API at the link above. Why is it abbreviated to Java SE (what does the SE stand for)?

Classes and Methods: Classes

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

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.

CS 152 Computer Programming Fundamentals Coding Standards

Software and Programming 1

Introduction to Computer Science Unit 2. Exercises

Remaining Enhanced Labs

Introduction to Computer Science Unit 2. Notes

Object Oriented Programming with Java

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

Methods and Data (Savitch, Chapter 5)

Classes. Classes as Code Libraries. Classes as Data Structures

Cmpt 135 Assignment 2: Solutions and Marking Rubric Feb 22 nd 2016 Due: Mar 4th 11:59pm

Problem Grade Total

Introduction to Computer Science I

Software and Programming 1

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.

CS61B - Exam 2 March 17, Consider the following example of a program that uses inheritance.

Java Object Oriented Design. CSC207 Fall 2014

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Carleton University COMP1406/1006, Summer 2013 Tutorial 2

We will work with Turtles in a World in Java. Seymour Papert at MIT in the 60s. We have to define what we mean by a Turtle to the computer

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Fundamentals of Programming Data Types & Methods

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Conditionals. For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations:

Introduction to Arrays

CMPSCI 187 / Spring 2015 Hangman

AP Computer Science Unit 1. Programs

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

CS 201, Fall 2016 Sep 28th Exam 1

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

AP Computer Science Homework Set 5 2D Arrays

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

Final Exam Practice. Partial credit will be awarded.

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

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)

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

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

Transcription:

More Methods GEEN163

There is method to her madness.

TuringsCraft Read the material in chapter 7 of the textbook Answer the questions in section 7 of the TuringsCraft tutorial 4 points for each correct answer 100 point maximum Due by midnight on Thursday (tomorrow)

Programming Homework A new programming assignment has been posted on Blackboard This program draws a picture of the night sky You are required to write a method

Chancellor s Forum The last Chancellor s Forum for students this academic year will be held from 5:30 7:30 p.m., on Thursday, March 17, in the Academic Classroom Building, room 101 Chancellor s Forums are designed to provide valuable information about university initiatives and strategic direction. Students are encouraged to attend the forums

Constructors are Usually Simple Most constructor methods simply copy the parameter to a class variable Some constructors set class variables to a constant Some constructors are more complex. The constructor for Scanner may have to check on a network connection

Multiple Constructors A class may have more than one constructor Different constructors must have a different number or type of parameters All constructors must have the same name as the class This is known as polymorphism

Two Constructors for Line public class Line { double slope; double intercept; // slope of the line // Y intercept of the line public Line(double tilt) { // constructor slope = tilt; intercept = 0.0; public Line(double tilt, double y) { // constructor slope = tilt; intercept = y;

Polymorphism Requires Different Parameters You cannot have the following two methods because they both have one double parameter public double half(double dog) { return dog/2.0; // Same as below public double half(double cat) { // Same as above return cat * 0.5;

Which statement calls the constructor? A. Line cheetah = new Line( 55.0); B. cheetah = Line( 66.0 ); C. Line( cheetah, 77.0 ); D. new cheetah = Line( 44.0 ); E. none of the above

Getters and Setters Some methods are very simple and only return or set an instance variable int wolf; // instance variable int getwolf() { return wolf; void setwolf(int lupus) { wolf = lupus;

Accessor or Getter Methods Accessor methods return some value from the object Accessor methods do not usually change anything in the object Getter methods usually have no parameters and return a value of the same type as the instance variable Examples of accessor methods include: String length() method

Modifier or Setter Methods Modifier methods change the state of an object A modifier method may just set the value of a single variable or may perform a lengthy sequence of actions Setter methods are often void methods and usually have one parameter

Example Class public class Widget { private int count = 0; public Widget( int num ) { count = num; public void inc() { count++; public int getcount() { return count; public void setcount( int value ) { count = value; // class data value // constructor // method to increment // accessor method // modifier method

Naming Convention Constructors must have the same name as the class Class names start with an uppercase letter Objects are written in lowercase Method names are in lowercase Accessor methods have names that can be used as nouns or getvariable Modifier methods have names that can be used as verbs or setvariable

Write with your team Given the following class, write get and set methods for nummembers public class TeamWork { private int nummembers; private String name;

Possible Solution public class TeamWork { private int nummembers; private String name; public int getnummembers() { return nummembers; public void setnummembers( int count ) { nummembers = count;

Calling Methods In Java you can use a method of an object by writing the object s name, a period, the name of the method. Widget thing = new Widget(); thing.whatever( 5 ); This calls the whatever method of Widget object thing passing it an integer 5 as a parameter

Inheritance You can extend an existing class to add new features We used inheritance to extend JApplet The new class has all of the data values and methods of the parent classes

Inheritance Example Some of our programs have input numbers from the JTextField The gettext method of JTextField only returns a string We can extend JTextField to add methods to get a double or an int

Extending JTextField public class NumField extends javax.swing.jtextfield { public int getint() { String text = gettext(); int number = Integer.parseInt(text); return number; public double getdouble() { String text = gettext(); double number = Double.parseDouble(text); return number;

Using NumField // class variables at the beginning NumField inyear = new NumField(); NumField inloan = new NumField();... public void actionperformed( java.awt.event.actionevent thing) { double loan = inloan.getdouble(); double m = inyear.getdouble() * 12.0; double pay = loan * etc.; answer.settext("monthly payments of $"+pay);

Parent Method Available You do not need the Java source code of a class to inherit from it You can extend a system class All of the original methods are available NumField inyear = new NumField(); inyear.settext("default");

Little Programs Methods are small programs A method often has parameters Parameters are data given to the method Most methods do NOT read from the keyboard Most methods do NOT display on the screen Methods usually return one value Methods are very useful to avoid writing the same code many times with different variables

Separate Names The names in a method have no connection to the names in the main program

Parameters Are Copied to Method // Main program int bird = 7, eagle; eagle = twice( bird ); // eagle becomes 14 // The twice method int twice( int turtle ) { // turtle is 7 int tortoise = 2 * turtle; return tortoise;

Two Kinds of Returns Value-Returning Always returns a single value to its caller and is called from within an expression. Void Never returns a value to its caller, and is called as a separate statement.

A void Method Call public class VoidMeth { public static void main(string[] args) { displaymessage( A ) ; //void method call System.out.println("Good Bye"); static void displaymessage( char grade) { System.out.println("I want an "+ grade ); This program displays I want an A Good Bye

return Statement All methods (except void methods and constructors) must return a value The return statement contains the value that is given back to the main program The return statement is often the last statement in the method return dog; return 47; return cat + mouse;

Running off the end When a void method runs past the last line of the method, it will return to the calling program A void method may use a return statement, but without any value on it return ;

Return Type The type of the return value is specified in the method header. The type in the header must match the type in the return statement public double mymethod(int pig, float goat) { double answer = ; return answer ; Type must match // method body here

Methods in Equations A method that returns a value is normally used in an equation int rtnmeth( double dog ) { // method definition return (int)dog + 2; int cat = 3 * rtnmeth( 5.75 ); // using the method

Return Value in an Expression int pig = 5, hog = 3, sow; sow = square( pig ) + hog; int square( int cat ) { return cat * cat;

Return Value in an Expression int pig = 5, hog = 3, sow; sow = square( 5 ) + hog; int square( int cat ) { return cat * cat;

Return Value in an Expression int pig = 5, hog = 3, sow; sow = square( 5 ) + hog; int square( int 5 ) { return cat * cat;

Return Value in an Expression int pig = 5, hog = 3, sow; sow = square( 5 ) + hog; int square( int 5 ) { return 5 * 5 ;

Return Value in an Expression int pig = 5, hog = 3, sow; sow = square( 5 ) + hog; int square( int 5 ) { return 25 ;

Return Value in an Expression int pig = 5, hog = 3, sow; sow = 25 + hog; int square( int 5 ) { return 25 ;

Return Value in an Expression int pig = 5, hog = 3, sow; sow = 25 + 3 ; int square( int 5 ) { return 25 ;

Return Value in an Expression int pig = 5, hog = 3, sow; sow = 28 ; int square( int 5 ) { return 25 ;

What is displayed? public static void main(string[] cow) { int bunny = 7, hare; hare = what( bunny) + 2; System.out.println( hare ); int what( int rat ) { int mouse = rat 3; return mouse; A. 2 B. 3 C. 4 D. 6 E. 7

Example Method Assume you have a number between -1 and +1 and you want to scale it to be between 0 and 500 Consider a method that takes a double parameter between -1.0 and 1.0 and returns an int between 0 and 500

Method Header The parameter is double and the return type is int public int convert( double x ) It is useful to write the header of a method to help understand exactly what is going in to the method and what is being returned

Adding the Body The parameters go from -1.0 to 1.0 or a range of 2.0 and the output range is 500 Negative values of the parameter will be less than 250 and positive more than 250 public int convert( double x ) { return (int)(x * 250.0) + 250;

Calling a Method in the same Class A call to a method in the same class needs the method name followed by the arguments mymethod( a, b ); 45

Calling a Method in Another Class A call to a static method in the another class needs the class name, a period, the method name followed by the arguments YourClass.myStaticMethod( a, b ); Math and JOptionPane are examples of classes with static methods 46

Calling a Method in Another Class A call to a non-static method in the another class needs an object s variable name, a period, the method name followed by the arguments. YourClass myobject = new YourClass(); myobject.mydynamicmethod( a, b ); The Scanner class has non-static methods 47

What is displayed by this program? int deer = 2, bear = 7; // start here Geen163 myobj = new Geen163(); myobj.dowhat( deer, bear);... in class Geen163... void dowhat( int goat, int pig) { goat = goat + 3; System.out.println("goat="+goat+" pig="+pig); A. goat=2 pig=7 B. goat=5 pig=7 C. goat=7 pig=5 D. none of the above

Write a method to average two numbers Write a simple method (ignore any class definition for now) that averages two double numbers

Write a method to average two numbers The method will need two parameters of type double The return value of the method will be the average and should be a double

A method to average two numbers double average( double num1, double num2) { return (num1 + num2) / 2.0;

A method to average two numbers double average( double num1, double num2) { double avg = (num1 + num2) / 2.0; return avg;

Incorrect double average( double num1, double num2) { num1 = keyboard.nextdouble(); num2 = keyboard.nextdouble(); double avg = (num1 + num2) / 2.0; System.out.println( avg = + avg ); return avg;

Methods calling Methods int dog = 5, cat; cat = metha( dog ); int metha( int cow ) { // cow = 5 int bull = 2 * cow; steer = methb( bull ) return steer int methb( int lizard ) { return lizard + 3;

Methods calling Methods int dog = 5, cat; cat = metha( dog ); int metha( int cow ) { // cow = 5 int bull = 2 * cow; // bull = 10 steer = methb( bull ) return steer int methb( int lizard ) { return lizard + 3;

Methods calling Methods int dog = 5, cat; cat = metha( dog ); int metha( int cow ) { // cow = 5 int bull = 2 * cow; // bull = 10 steer = methb( bull ) return steer int methb( int lizard ) { // lizard = 10 return lizard + 3;

Methods calling Methods int dog = 5, cat; cat = metha( dog ); int metha( int cow ) { // cow = 5 int bull = 2 * cow; // bull = 10 steer = methb( bull ) return steer int methb( int lizard ) { // lizard = 10 return lizard + 3; // returns 13

Methods calling Methods int dog = 5, cat; cat = metha( dog ); int metha( int cow ) { // cow = 5 int bull = 2 * cow; // bull = 10 steer = methb( bull ) // steer 13 return steer int methb( int lizard ) { // lizard = 10 return lizard + 3; // returns 13

Methods calling Methods int dog = 5, cat; cat = metha( dog ); int metha( int cow ) { // cow = 5 int bull = 2 * cow; // bull = 10 steer = methb( bull ) // steer 13 return steer // returns 13 int methb( int lizard ) { // lizard = 10 return lizard + 3; // returns 13

Methods calling Methods int dog = 5, cat; cat = metha( dog ); // cat = 13 int metha( int cow ) { // cow = 5 int bull = 2 * cow; // bull = 10 steer = methb( bull ) // steer 13 return steer // returns 13 int methb( int lizard ) { // lizard = 10 return lizard + 3; // returns 13

What is displayed? int metha(int dog) { int cat = methb( dog + 1 ); A. 4 return cat; B. 5 int methb(int goat) { C. 10 return goat * 2; D. none of the above public static void main(string[] x) { int fish = metha( 4 ); System.out.println( fish );

Changing the Parameters Does Not Change the Calling Arguments If a method changes the value of a parameter variable, it does not change the value of the variable in the calling program. The values of the argument variables are copied to the method parameters when the method is called, but are not copied back when the method returns.

Parameter Values Not Changed public class ModParm { public static void main(string[] args ){ int a = 5, b = 47, c = -1; System.out.println("main a="+a+" b="+b+" c="+c); c = example( a, b ); System.out.println("main a="+a+" b="+b+" c="+c); static int example( int x, int y ) { x = 13; // parameter changed System.out.println("example x="+x+" y="+y); return x + y; Output main a=5 b=47 c=-1 example x=13 y=47 main a=5 b=47 c=60

What is printed by this program? int deer = 2, bear = 7; // start here Geen163 myobj = new Geen163(); myobj.dowhat( deer, bear); System.out.println(" deer="+deer);... in class Geen163... void dowhat( int goat, int pig) { goat = goat + 3; System.out.print("goat="+goat); A. goat=2 deer=7 B. goat=5 deer=2 C. goat=5 deer=5 D. none of the above

TuringsCraft Read the material in chapter 7 of the textbook Answer the questions in section 7 of the TuringsCraft tutorial 4 points for each correct answer 100 point maximum Due by midnight on Thursday (tomorrow)

Programming Homework A new programming assignment has been posted on Blackboard This program draws a picture of the night sky You are required to write a method

Chancellor s Forum The last Chancellor s Forum for students this academic year will be held from 5:30 7:30 p.m., on Thursday, March 17, in the Academic Classroom Building, room 101 Chancellor s Forums are designed to provide valuable information about university initiatives and strategic direction. Students are encouraged to attend the forums