COMP 110-001 More About Classes Yi Hong May 22, 2015.

Slides:



Advertisements
Similar presentations
Constructors & An Introduction to Methods. Defining Constructor – Car Example Public class car { String Model; double speed; String colour; { Public Car.
Advertisements

CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Math class methods & User defined methods Introduction to Computers and Programming in JAVA: V
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
COMP 110 Classes Tabitha Peck M.S. February 20, 2008 MWF 3-3:50 pm Philips
26-Jun-15 Methods. About methods A method is a named group of declarations and statements You execute those declarations and statements by calling the.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
 To be able to write larger programs ◦ By breaking them down into smaller parts and passing data between the parts.  To understand the concepts of Methods.
Defining Classes and Methods Chapter 4.1. Key Features of Objects An object has identity (it acts as a single whole). An object has state (it has various.
Introduction to Methods
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
Unit 2: Java Introduction to Programming 2.1 Initial Example.
COMP Classes Yi Hong May 22, Announcement  Lab 2 & 3 due today.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Classes, Objects, and Methods
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
COMP Mid-Term Review Yi Hong May 27, 2015.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
Introduction to programming in the Java programming language.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall Java Programming.
Java methods Methods break down large problems into smaller ones Your program may call the same method many times saves writing and maintaining same code.
COMP 110 Classes Luv Kohli October 1, 2008 MWF 2-2:50 pm Sitterson 014.
COMP 110: Introduction to Programming Tyler Johnson Feb 16, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Catie Welsh February 23,  Lab 4 due on Friday  Lab 5 will be assigned on Friday 2.
Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Department of Computer Engineering Methods Computer Programming for International Engineers.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
COMP 110 More about classes Luv Kohli October 3, 2008 MWF 2-2:50 pm Sitterson 014.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Information and Computer Sciences University of Hawaii, Manoa
Lecture 4b Repeating With Loops
Michele Weigle - COMP 14 - Spr 04 Catie Welsh February 21, 2011
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Suppose we want to print out the word MISSISSIPPI in big letters.
Methods Chapter 6.
Loop Structures.
Class Structure 16-Nov-18.
Classes, Objects, and Methods
Defining Classes and Methods
The for-loop and Nested loops
Class Structure 7-Dec-18.
Class Structure 2-Jan-19.
Announcements Program 2 is due tomorrow by noon Lab 4 was due today
Class Structure 25-Feb-19.
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Defining Classes and Methods
In this class, we will cover:
Classes, Objects and Methods
Announcements Assignment 2 and Lab 4 due Wednesday.
Methods/Functions.
Corresponds with Chapter 5
Presentation transcript:

COMP More About Classes Yi Hong May 22, 2015

Review public class Student { public String name; public int classYear; public double gpa; public String major; //... public String getMajor() { return major; } public void increaseYear() { classYear++; } //... } Class Name: Student - name: String - year: int - gpa: double - major: String - credits: int - gpaSum: double + getName(): String + getMajor(): String + printData(): void + increaseYear(): void + calcGpa(double grade): void

Today  Methods  Code block and variable scope

 Class: a definition of a kind of object  Object: an instance of a class Contains instance variables (data) and methods  Methods Performs actions defined by a set of statements 4 Classes, Objects, and Methods

 Two kinds of methods Methods that return a value Examples: String’s substring() method, String’s indexOf() method, etc. Methods that return nothing Perform some action other than returning an item Example: System.out.println() 5 Methods

public String getMajor() { return major; } public void increaseYear() { classYear++; } 6 Methods returns a String returns nothing return type

public void increaseYear() { classYear++; }  Method heading: public: no restriction on how to use the method (more details later) void: a void method that returns nothing Method name Method parameters (no parameters in this example)  Method body: statements executed when the method is called (invoked) Must be inside a pair of braces {} 7 Defining Methods That Return Nothing

 As usual, inside a block (defined by braces), you can have multiple statements public void printData() { System.out.println(“Name: ” + name); System.out.println(“Major: ” + major); System.out.println(“GPA: ” + gpa); } 8 Example: Method printData

Example of Method with Parameters public void increaseYear(int increment) { classYear += increment; } public void increaseYear(int increment, boolean check) { if (check && classYear + increment <= MaxYear ) { classYear += increment; } }  Parameters are used to hold the values that you pass to the method  Multiple parameters are separated by comma Data typeName of parameter

 Object, followed by dot, then method name, then () Order, type, and number of arguments must match parameters specified in method heading  Use them as Java statements Student jack = new Student(); jack.classYear = 1; jack.increaseYear(); System.out.println(“Jack’s class year is ” + jack.classYear); 10 Calling Methods That Return Nothing

public String getMajor() { return major; }  Method heading: public: no restriction on how to use the method (more details later) Type: the data type of value that the method returns Method name & parameters  Method body: statements executed Must be inside a pair of braces {} Must have a return statement 11 Defining Methods That Return a Value

 A method that returns a value must have at least one return statement  Terminates the method’s execution, and provides a value returned by the method. More statements follow the return statement will not be executed  Syntax: return Expression;  Expression can be any expression that produces a value of the type specified in the heading of the method 12 return Statement

 Example: public String getClassYear() { if (classYear == 1) return “Freshman”; else if (classYear == 2) return “Sophomore”; else if... } 13 Methods That Return a Value  A better one: public String getClassYear() { String str = “”; if (classYear == 1) str = “Freshman”; else if (classYear == 2) str = “Sophomore”; else if... return str; }

 Object, followed by dot, then method name, then () (the same as before)  Use them as a value of the type specified by the method’s return type Student jack = new Student(); jack.major = “Computer Science”; String major = jack.getMajor(); System.out.println(“Jack’s full name is ” + jack.getName()); System.out.println(“Jack’s major is ” + major); 14 Calling Methods That Return a Value

 Can also be used in methods that return nothing  Terminates the method  Syntax: Return; public void increaseYear() { if (classYear >= 4) return; classYear++; } 15 return Statement

Summary of Method Definitions  Syntax Return_Type void (don’t need a return statement, but it can have one if you want to end the method invocation before the physical end of the code: return; ) a data type (Statements must contain at least one return statement of the form: return Expression; )

Calling Methods from Methods  In a method’s body, we can call another method receiving_object.method();  If calling a method in the same class, we do not need receiving_object: method();  Alternatively, use the this keyword this.method();

this  Within a class definition, this is a name for the receiving object  The object is understood to be there, but its name usually is omitted this.name this.major this.getMajor()  See textbook p.282 for details

Code Block  A section of code enclosed by { … }  For grouping purpose if ( x < 0 ) { isPositive = false; x = -x; } for(int i = 0; i<10; i++) { System.out.println(“*”); }

Code Block  Code blocks can be nested public class Hello { public static void main(String arg[]) { System.out.println("Hello.");Outer block } } public class Hello{ public static void main(String arg[]) { System.out.println("Hello."); Inner block } }

Another Example of Code Block for(int i = 0; i<100; i++) { if ( i % 2 ==0 ) { System.out.println(i + " is even");Outer block } } for(int i = 0; i<100; i++) { if ( i % 2 ==0 ) { System.out.println(i + " is even"); Inner block } }

Variable Scope  The scope of a variable is the part of the program over which the variable name can be referenced  Variables here include local / instance variables, and method parameters  Two rules: You cannot refer to a variable before its declaration Variables defined in a block are only accessible within the block

Variable Scope  Rule 1: (Use after definition) s.nextInt(); ….. Scanner s = new Scanner(System.in); i = 6; …… int i; ✗ ✗

Variable Scope  Rule 1: (Use after definition) Method parameters (ready for use in the method body ) public Color getColorFromString( String input ) { // input is available for using in the whole method body … }

Variable Scope  Rule 2: Variables defined in a block are only accessible within the block int outer = 1; { int inner = 2; System.out.println("inner = " + inner); System.out.println("outer = " + outer); } System.out.println("inner = " + inner); System.out.println("outer = " + outer); Cannot reference inner here ✗

Variable Scope  Rule 2: Variables defined in a block are only accessible from within the block int outer = 1; { int inner = 2; System.out.println("inner = " + inner); System.out.println("outer = " + outer); } int inner = 3;// why I can define inner again? System.out.println("inner = " + inner); System.out.println("outer = " + outer); inner = 2 outer = 1 inner = 3 outer = 1

 What is the scope of instance variables? Variable Scope public class Student { public String name; public int classYear; public double GPA; public String major; //... public String getMajor() { return major; } public void increaseYear() { classYear++; } Scope

public class Student { public String name; public int classYear; public String major; public void printInfo() { String info = name + “: ” + major + “: ” + classYear ; System.out.println(info); } public void increaseYear(int inc) { classYear += inc; String info = “classYear updated”; System.out.println(info); } 28 Revisit Local and Instance Variables

Next Class  No Class next Monday (Memorial Day)  We will have Lab 4 & 5 next Tuesday  Homework 2 due next Tuesday