Lecture 5- Classes, Objects and Methods

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Starting Out with Java: From Control Structures through Objects Fourth.
Chapter 6: A First Look at classes. Object-Oriented Programming  Object-oriented programming is centered on creating objects rather than procedures.
1 Fall 2009ACS-1903 Methods – Ch 5 A design technique referred to as stepwise refinement (or divide and conquer, or functional decomposition) is used to.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
Copyright © 2012 Pearson Education, Inc. Chapter 6 Modularizing Your Code with Methods.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Introduction to Methods
Chapter 6: A First Look at Classes
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
A First Look At Classes Chapter 6. Procedural Programming In procedural- programming all the program functionality is written in a few modules of code.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: From Control Structures through Objects Third Edition.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Starting Out with Java: From Control Structures through Objects.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 5, Methods Java How to Program, Late Objects Version, 10/e
Methods Chapter Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter 5: Methods.
Chapter 4 Introduction to Classes, Objects, Methods and strings
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
© 2010 Pearson Addison-Wesley. All rights reserved. 6-1 Chapter Topics Chapter 6 discusses the following main topics: –Classes and Objects –Instance Fields.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Lecture 19: Introduction to Classes Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5-1 Why Write Methods? Methods are commonly used to break a problem down.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 3 A First Look at Classes and Objects.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Chapter 5 : Methods. Why Write Methods?  Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
Chapter 5 : Methods Part 2. Returning a Value from a Method  Data can be passed into a method by way of the parameter variables. Data may also be returned.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
Introduction to Constructors Lecture # 4. Copyright © 2011 Pearson Education, Inc. 3-2 Arguments Passed By Value In Java, all arguments to a method are.
Chapter 6 A First Look at Classes. 2 Contents 1. Classes and objects 2. Instance Fields and Methods 3. Constructors 4. Overloading Methods and Constructors.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 3: A First Look at Classes and Objects.
Chapter 6 A First Look at Classes. 2 Contents 1. Classes and objects 2. Instance Fields and Methods 3. Constructors 4. Overloading Methods and Constructors.
Chapter 5 Methods. 2 Contents 1. Introduction to Methods 2. Passing Arguments to a Method 3. More about Local Variables 4. Returning a Value from a Method.
A Second Look at Classes and Objects - 1 Static Class Members
Chapter 3 Classes & Objects
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 3: Using Methods, Classes, and Objects
by Tony Gaddis and Godfrey Muganda
Introduction to Classes
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Methods.
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
if-else-if Statements
Chapter Topics Chapter 5 discusses the following main topics:
Starting Out with Java: From Control Structures through Objects
Introduction to Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Starting Out with Java: From Control Structures through Objects
6 Chapter Functions.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Today’s topics UML Diagramming review of terms
Chapter 6 – Methods Topics are:
Starting Out with Java: From Control Structures through Objects
Object Oriented Programming in java
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Classes, Objects and Methods
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Chapter 5: Methods Starting Out with Java: From Control Structures through Objects Third Edition by Tony Gaddis.
Lecture 8 Object Oriented Programming (OOP)
Chapter 6: A First Look at classes
Presentation transcript:

Lecture 5- Classes, Objects and Methods CS 140 Introduction to Computer Science Lecture 5- Classes, Objects and Methods Dr. Sampath Jayarathna Cal Poly Pomona

Objects and Classes An object exists in memory, and performs a specific task. Objects have two general capabilities: Objects can store data. The pieces of data stored in an object are known as fields. Objects can perform operations. The operations that an object can perform are known as methods.

Objects and Classes You have already used the following objects: Scanner objects, for reading input String objects, for text variables When a program needs the services of a particular type of object, it creates that object in memory, and then calls that object's methods as necessary.

Objects and Classes Classes: Where Objects Come From A class is code that describes a particular type of object. It specifies the data that an object can hold (the object's fields), and the actions that an object can perform (the object's methods). You can think of a class as a code "blueprint" that can be used to create a particular type of object.

Objects and Classes This expression creates a Scanner object in memory. Example: Scanner keyboard = new Scanner(System.in); The object's memory address is assigned to the keyboard variable. keyboard variable Scanner object

The box variable holds the address of the Rectangle object. Creating an object ClassName objectName = new ClassName(); Rectangle box = new Rectangle (); A Rectangle object The box variable holds the address of the Rectangle object. length: 0.0 address width: 0.0

Instance Fields and Methods Instance fields and instance methods require an object to be created in order to be used. Note that each room represented in this can have different dimensions. Rectangle kitchen = new Rectangle(); Rectangle bedroom = new Rectangle(); Rectangle den = new Rectangle();

States of Three Different Rectangle Objects The kitchen variable holds the address of a Rectangle Object. length: 10.0 address width: 14.0 The bedroom variable holds the address of a Rectangle Object. length: 15.0 address width: 12.0 The den variable holds the address of a Rectangle Object. length: 20.0 address width: 30.0

Access Specifiers An access specifier is a Java keyword that indicates how a field or method can be accessed. public When the public access specifier is applied to a class member, the member can be accessed by code inside the class or outside. private When the private access specifier is applied to a class member, the member cannot be accessed by code outside the class. The member can be accessed only by methods that are members of the same class.

Writing the Code for the Class Fields public class Rectangle { public double length; // field length public double width; // field width public static void main(String[] args) Rectangle box = new Rectangle(); box.length = 4.3; // set values box.width = 5.2; // set values } Object.fieldname to access public fields

Private Class Fields Rectangle box = new Rectangle(); Need public methods to access the fields public class Rectangle { private double length; // field length private double width; // field width public static void main(String[] args) Rectangle box = new Rectangle(); box.length = 4.3; // set values box.width = 5.2; // set values } Error! Can’t access private fields

Instance Fields and Methods Fields and methods that are declared as previously shown are called instance fields and instance methods. Objects created from a class each have their own copy of instance fields. Instance methods are methods that are not declared with a special keyword, static.

Activity 10 Create a class Vehicle Create 4 relevant data fields for the class Vehicle. Write main method and create following objects from the class Vehicle car suv semitruck schoolBus Assign relevant data values for the object schoolBus and display the results.

Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer. Methods simplify programs. If a specific task is performed in several places in the program, a method can be written once to perform that task, and then be executed anytime it is needed. This is known as code reuse.

Parts of a Method Header Method modifiers public—method is publicly available to code outside the class static—method belongs to a class, not a specific object. Return type—void or the data type from a value- returning method Method name—name that is descriptive of what the method does Parentheses—contain nothing or a list of one or more variable declarations if the method is capable of receiving arguments.

Header for the setLength Method Return Type Notice the word static does not appear in the method header designed to work on an instance of a class (instance method). Method Name Access specifier public void setLength (double len) { length = len; } Parameter variable declaration

Calling the setLength Method Rectangle box = new Rectangle (); box.setLength(10.0); The box variable holds the address of the Rectangle object. A Rectangle object length: 10.0 address width: 0.0 This is the state of the box object after the setLength method executes.

Writing the Code for the Class Fields public class Rectangle { private double length; // field length private double width; // field width public void setLength(double len) length = len; } public static void main(String[] args) Rectangle box = new Rectangle(); box.setLength(5.5);

void Methods and Value-Returning Methods A void method is one that simply performs a task and then terminates. System.out.println("Hi!"); A value-returning method not only performs a task, but also sends a value back to the code that called it. String name = “Cal Poly”; int number = name.length();

Defining a void Method To create a method, you must write a definition, which consists of a header and a body. The method header, which appears at the beginning of a method definition, lists several important things about the method, including the method’s name. The method body is a collection of statements that are performed when the method is executed.

Two Parts of static Method Declaration Header public static void displayMesssage() { System.out.println("Hello"); } Body

Parts of a static Method Header Method Modifiers Return Type Method Name Parentheses public static void displayMessage () { System.out.println("Hello"); }

Calling a static Method A method executes when it is called. The main method is automatically called when a program starts, but other methods are executed by method call statements. displayMessage(); Notice that the method modifiers and the void return type are not written in the method call statement. Those are only written in the method header.

Activity 11 (will be included in quiz grade) Create a static method called displayMyRecord() In this method, display the following information Your name Your Age Your City Your favorite movie, TV show, singer/song Call above method from your main() method

Passing Arguments to a Method Values that are sent into a method are called arguments. System.out.println("Hello"); The data type of an argument in a method call must correspond to the variable declaration in the parentheses of the method declaration. The parameter is the variable that holds the value being passed into a method. By using parameter variables in your method declarations, you can design your own methods that accept data this way.

Passing 5 to the displayValue Method public static void displayValue(int num) { System.out.println("The value is " + num); } The argument 5 is copied into the parameter variable num. The method will display The value is 5

Argument and Parameter Data Type Compatibility When you pass an argument to a method, be sure that the argument’s data type is compatible with the parameter variable’s data type. Java will automatically perform widening conversions, but narrowing conversions will cause a compiler error. double d = 1.0; displayValue(d); Error! Can’t convert double to int

Passing Multiple Arguments The argument 5 is copied into the num1 parameter. The argument 10 is copied into the num2 parameter. showSum(5, 10); public static void showSum(double num1, double num2) { double sum; //to hold the sum sum = num1 + num2; System.out.println("The sum is " + sum); } NOTE: Order matters!

Activity 12 (will be included in quiz grade) Update the static static method displayMyRecord() to pass all the information (name, age, city, movie, tvshow, singer, song) below as parameters In this method, display the following information Your name Your Age Your City Your favorite movie, TV show, singer/song Call above method from your main() method passing the required parameter values.

Arguments are Passed by Value In Java, all arguments of the primitive data types are passed by value, which means that only a copy of an argument’s value is passed into a parameter variable. A method’s parameter variables are separate and distinct from the arguments that are listed inside the parentheses of a method call. If a parameter variable is changed inside a method, it has no affect on the original argument.

More About Local Variables A local variable is declared inside a method and is not accessible to statements outside the method. Different methods can have local variables with the same names because the methods cannot see each other’s local variables. A method’s local variables exist only while the method is executing. When the method ends, the local variables and parameter variables are destroyed and any values stored are lost. Local variables are not automatically initialized with a default value and must be given a value before they can be used.

Defining a Value-Returning Method Data can be passed into a method by way of the parameter variables. Data may also be returned from a method, back to the statement that called it. public static int sum(int num1, int num2) { int result; result = num1 + num2; return result; } Return type The return statement causes the method to end execution and it returns a value back to the statement that called the method. This expression must be of the same data type as the return type

Calling a Value-Returning Method total = sum(value1, value2); public static int sum(int num1, int num2) { int result; result = num1 + num2; return result; } 40 20 60

Activity 13 (will be included in quiz grade) Create a method called calculator() You are going to pass an appropriate operator (+, -, *, /, %) and 2 operands x and y to this method. Calculate the resulting value based on the operand and operators and return the value. Create 5 calls by sending each operand and x, y as parameters and display the result.

Returning a booleanValue Sometimes we need to write methods to test arguments for validity and return true or false public static boolean isValid(int number) { boolean status; if(number >= 1 && number <= 100) status = true; else status = false; return status; } Calling code: int value = 20; If(isValid(value)) System.out.println("The value is within range"); System.out.println("The value is out of range");

Returning a Reference to a String Object customerName = fullName("John", "Martin"); public static String fullName(String first, String last) { String name; name = first + " " + last; return name; } address Local variable name holds the reference to the object. The return statement sends a copy of the reference back to the call statement and it is stored in customerName. “John Martin”

Accessor and Mutator Methods Because of the concept of data hiding, fields in a class are private. The methods that retrieve the data of fields are called accessors. The methods that modify the data of fields are called mutators. Each field that the programmer wishes to be viewed by other classes needs an accessor. Each field that the programmer wishes to be modified by other classes needs a mutator.

Accessors and Mutators For the Rectangle example, the accessors and mutators are: setLength : Sets the value of the length field. public void setLength(double len) … setWidth : Sets the value of the width field. public void setLength(double w) … getLength : Returns the value of the length field. public double getLength() … getWidth : Returns the value of the width field. public double getWidth() … Other names for these methods are getters and setters.

Getters and Setters for Rectangle Class public class Rectangle { private double width; private double length; public void setWidth(double w) { width = w; } public void setLength(double len) { length = len; public double getWidth() { return width; public double getLength() { return length; public double getArea() { return length * width;

Calling the instance methods public class Rectangle { … public static void main(String[] args) Rectangle box = new Rectangle(); box.setLength(5.5); box.setWidth(2.4); double boxWidth = box.getWidth(); double boxLength = box.getLength(); System.out.println(box.getArea()); }

Activity 14 (will be included in quiz grade) Create a class called Employee The fields are name, age, designation, and salary. Create getters and setters for the Employee class Create a method called displayRecord() and display the results of these objects Create another class called Driver Create 3 employees and set their data fields through the setters of Employee class. Your main method is in the Driver class.