Classes, Objects, and Methods

Slides:



Advertisements
Similar presentations
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Advertisements

Object Reference. Variables: Class Type vs. Primitive Type What does a variable hold? –primitive type value of the variable –class type memory address.
1 Chapter Three Using Methods. 2 Objectives Learn how to write methods with no arguments and no return value Learn about implementation hiding and how.
1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference l Parameter passing Classes, Objects, and Methods.
Chapter 4 Defining Classes I Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Road Map Introduction to object oriented programming. Classes
Chapter 41 Defining Classes and Methods Chapter 4.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 4 Defining Classes I Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.
Information Hiding and Encapsulation
Chapter 11: Classes and Data Abstraction
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.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Defining Classes and Methods Chapter 4. Objectives become familiar with the concept of –a class –an object that instantiates the class learn how to –define.
Classes, Objects, and Methods
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Classes CS 21a: Introduction to Computing I First Semester,
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Bryce Canyon, Utah CSE 114 – Computer Science I Objects and Reference.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.
Day 5. Task: Implement your vending machine code into the program with JOptionPane I/O (modify it) it to me.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Day Class Definitions and Methods Local & global variables, parameters & arguments,
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
COMP 150: Introduction to Object-Oriented Programming Lecturer: Dr. AJ Bieszczad 4-1 Chapter 4 l Class and Method Definitions l Information Hiding and.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods.
Defining Classes and Methods Chapter 4. Object-Oriented Programming Our world consists of objects (people, trees, cars, cities, airline reservations,
Chapter 41 Defining Classes and Methods Chapter 4.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
COMP 110 Worksheet review, debugger Luv Kohli September 29, 2008 MWF 2-2:50 pm Sitterson 014.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
COMP 110 Classes Luv Kohli October 1, 2008 MWF 2-2:50 pm Sitterson 014.
Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void.
Lecture 08. Since all Java program activity occurs within a class, we have been using classes since the start of this lecture series. A class is a template.
1 Week 8 l Methods l Parameter passing Methods. 2 Using Methods l Methods are actions that an object can perform. l To use a method you invoke or call.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 05: Classes and Data Abstraction.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Defining Classes and Methods
Michele Weigle - COMP 14 - Spr 04 Catie Welsh February 21, 2011
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
Outline Class and Method Definitions
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Defining Classes and Methods
Classes, Objects, and Methods
Defining Classes and Methods
Defining Classes and Methods
Chapter 4 Defining Classes I
Object Oriented Programming in java
Defining Classes and Methods
Defining Classes and Methods
Classes, Objects and Methods
Presentation transcript:

Classes, Objects, and Methods Chapter 4 Classes, Objects, and Methods Class and Method Definitions Information Hiding and Encapsulation Objects and Reference Parameter Passing

Classes Classes are the fundamental building blocks of Java. A class is the definition of a kind of object. It’s like an outline or plan for constructing specific objects. Example: An Automobile class (next slide). An object that satisfies the Automobile definition instantiates the Automobile class. A class specifies what kinds of data objects of the class have. Each object has the same data items but can have different values. A class also specifies what methods each object will have. All objects of the same class have the exact same methods.

Class as an Outline First Instantiation: Object name: patsCar amount of fuel: 10 gallons speed: 55 miles per hour license plate: “135 XJK” Objects that are instantiations of the class Class Definition Second Instantiation: Object name: suesCar amount of fuel: 14 gallons speed: 0 miles per hour license plate: “SUES CAR” Class Name: Automobile Data: amount of fuel ________ speed ________ license plate ________ Methods (actions): increaseSpeed: How: Press on gas pedal. stop: How: Press on brake pedal. Third Instantiation: Object name: ronsCar amount of fuel: 2 gallons speed: 75 miles per hour license plate: “351 WLF”

Objects An object is a variable that is a named instance of a class. The class is its type. Think of the String and Scanner classes. An object has both data and methods. The data items and methods are called members of the object. Data items are also called fields or instance variables. We use instance variables. Using a method means invoking or calling the method. An object invokes a method with the dot operator: objectVariableName.method() objectVariableName is the calling object.

Example: String Class String is a class. It stores a sequence of characters. Its length method returns the number of characters. Example: Read characters typed in by a user from the keyboard and output the number of characters entered. Scanner keyboard = new Scanner(System.in); String userInput; userInput = keyboard.nextLine(); System.out.println(userInput.length());

Class Files Each Java class definition should be a separate file. Use the same name for the class and the file except add “.java” to the file name. Good programming practice: Start the class and file name with a capital letter and capitalize inner words. Example: MyClass.java for the file containing the class MyClass. For now, put all the classes you need to run a program in the same directory.

Instance Variables SpeciesFirstTry class (page 225) has three instance variables: name, population, and growthRate: public means that there are no restrictions on how these instance variables are used. Later we’ll see that these should be declared private instead of public. public String name; public int population; public double growthRate;

Instantiating (Creating) Objects Syntax: ClassName instanceName = new ClassName(); Note the keyword new. Example for the class SpeciesFirstTry: SpeciesFirstTry speciesOfTheMonth = new SpeciesFirstTry(); Public instance variables can be accessed using the dot operator: SpeciesOfTheMonth.name = "Klingon ox";

Using Methods A method is an action an object can perform. To use a method, an object invokes or calls it. Example of a method call: speciesOfTheMonth.writeOutput(); There are two basic kinds of methods: Methods that return a single value. Methods that do some action other than returning a value. These methods are called void methods. calling object method name parameter list in parentheses (parameters give info to the method, but in this example there are no parameters)

Return Type of Methods All methods require that a return type be specified. Return types may be: a primitive data type, such as char, int, double, etc. a class, such as String, SpeciesFirstTry, etc. void if no value is returned. You can use a method any place where it is legal to use its return type. Example: The nextInt() method of the Scanner class returns an integer. So int next = keyboard.nextInt(); is a legal statement.

void Method Example The definition of the writeOutput method of SpeciesFirstTry: Assuming instance variables name, population, and growthRate have been defined and assigned values, this method performs an action (writes values to the screen) but does not return a value. public void writeOutput() { System.out.println("Name = " + name); System.out.println("Population = " + population); System.out.println("Growth rate = " + growthRate + "%"); }

Return Statement Methods that return a value must execute a return statement that includes the value to return. Example: The populationIn10 method on page 226.

Method and Class Naming Conventions Good Programming Practices Use verbs to name void methods. They perform actions. Use nouns to name methods that return values. They create (return) values which are things. Start class names with capital letters. Start method names with lower-case letters.

The main Method A program written to solve a problem (rather than define an object) is written as a class with one void method main. When you run the program, you invoke the main method. Example: SpeciesFirstTryDemo on page 227. Note the basic structure: public class SpeciesFirstTryDemo { public static void main(String[] args) { <statements that define the main method> } }

The Reserved Word this The word this has a special meaning for objects. It is a reserved word, which means you should not use it as an identifier for a variable, class, or method. Other examples of reserved words are int, while, void, and so on. (See Appendix 1.) this stands for the name of the calling object. Java allows you to omit this. It is automatically understood that an instance variable name without the keyword this refers to the calling object.

Example Using this The writeOutput method of SpeciesFirstTry including the keyword this: public void writeOutput() { System.out.println("Name = " + this.name); System.out.println("Population = " + this.population); System.out.println("Growth rate = " + this.growthRate + "%"); } this refers to the name of the calling object that invokes the writeOutput method.

Local Variables and Blocks A block (a compound statement) is the set of statements between a pair of matching braces (curly brackets). A variable declared inside a block is known only inside that block. It is local to the block; therefore, it is called a local variable. When the block is finished executing, local variables disappear. References to a local variable outside the block cause a compiler error.

Local Variables and Blocks Some programming languages (such as C and C++) allow the variable name to be reused outside the local block. It is confusing and not recommended, but it is allowed. However, a variable name in Java can be declared only once for a method. Although the variable does not exist outside the block, other blocks in the same method cannot reuse the variable’s name.

When and Where to Declare Variables Declaring variables outside all blocks but within the method definition makes them available within all the blocks. Good Programming Practices: Declare variables just before you use them. Initialize variables when you declare them. Do not declare variables inside loops. It takes time during execution to create and destroy variables, so it is better to create them just once for loops. It’s OK to declare loop counters in the Initialization field of for loops as in for(int i=0; i < 10; i++)… The Initialization field executes only once when the for loop is first entered. The counter is then local to the for loop.

Passing Values to a Method: Parameters Some methods can be more flexible and useful if we pass them input values. Input values for methods are called passed values or parameters. Parameters and their data types must be specified inside the parentheses of the heading in the method definition. These are called formal parameters or simply parameters. The calling object must put values of the same data type, in the same order, inside the parentheses of the method invocation. These are called actual parameters or arguments.

Parameter Passing Example //Definition of method to double an integer public int doubleValue(int numberIn) { return 2 * numberIn; } //Invocation of the method somewhere in main int next = keyboard.nextInt(); System.out.println("Twice next = " + doubleValue(next)); What is the (formal) parameter in the method definition? numberIn What is the argument in the method invocation? next

Call-By-Value: Primitive Data Types as Parameters When a method is called, the value of each argument is copied (assigned) to its corresponding formal parameter. The number of arguments must be the same as the number of formal parameters. The data types of the arguments must be the same as the data types of the formal parameters and in the same order. Formal parameters are initialized to the values passed. Formal parameters are local to their method. Variables used as arguments cannot be changed by the method. The method gets only a copy of the variable’s value.

Summary of Class Definition Syntax /** Class description */ public class Class_Name { <instance variable declarations> //Method definitions of the form: Method description Precondition (what's true before the method is invoked) Postcondition (what the method does) public returnType Method_Name(type1 parameter1, ...) { <statements defining the method> }

Information Hiding and Encapsulation Cornerstones of Object-Oriented Programming (OOP). Both are forms of abstraction. Information hiding Protect data inside an object. Design a method for use without a knowledge of its code. Encapsulation Hide details of a class definition. Divide a class into two parts: user interface and implementation.

public and private public private Any other class or program can directly access or change a public instance variable. Any other class or program can invoke a public method. private Only a method in the same class can access a private instance variable. Only a method in the same class can invoke a private method. Instance variables should be private to prevent inappropriate changes.

Accessors and Mutators accessor methods—public methods that allow instance variables to be read. mutator methods—public methods that allow instance variables to be modified. Mutator methods should always check to make sure that changes are appropriate. Providing mutator methods is much better than making instance variables public because a method can check to make sure that changes are appropriate.

Precondition and Postcondition Comments Efficient and standard way to tell what a method does. precondition—states conditions that must be true before a method is invoked. postcondition—tells the effect of a method call. Example: The projectedPopulation method. /** Precondition: "years" is a nonnegative integer. Postcondition: Returns the projected population after the specified number of years. */ Note that the words preconditions and postconditions are not always used, particularly if the only postcondition describes the return value of the method.

Assertion Checks assertion—a statement that should be true if there are no mistakes in the program. Preconditions and postconditions are examples of assertions. Can use assert to see if assertion is true. Syntax: assert Boolean_Expression; Example: assert n >= limit; If assertion is false when checked, the program ends and an error message is printed. Assertion checking can be turned on and off. The exact way to enable or disable assertions depends on your development environment. See page 252.

A Well-Encapsulated Class Definition Implementation: Private instance variables Private constants Private methods Bodies of public and private methods Interface: Comments Headings of public methods Public defined constants Programmer who uses the class A programmer who uses the class can access the instance variables only indirectly through public methods and constants.

Formalized Abstraction: ADTs ADT: Abstract Data Type An object-oriented approach used by several languages. A term for class implementation. A container for both data items and methods to act on the data. Implements information hiding and encapsulation. Provides a public user interface so the user knows how to use the class. Provides descriptions, parameters, and names of its methods. Implementation: Private instance variables. Method definitions are usually public but always hidden from the user. The user cannot see or change the implementation. The user sees only the interface.

Information Hiding, Encapsulation, Abstract Data Type (ADT) Summary Basically refer to the same general idea. The data and actions are combined into a single item (a class object, for example). The details of the implementation are hidden. Spare the programmer who uses your class from needing to read the details of how your class is implemented. javadoc—a program that takes a properly documented class and produces a nice user interface. See Appendix 9.

Sound Complicated? Not really! Just create classes as previously described, except: Use the private modifier when declaring instance variables. Do not give the user the class definition file. Do give the user the interface—a file with just the class and method descriptions and headings. The headings give the names and parameters of the methods. The descriptions tell the user how to use the class and its methods. This is all the user needs to know.

UML Class Diagrams Class name Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void + stop(double howHardPress): void Instance variables Methods (actions) - private + public Universal Modeling Language (UML) class diagram—a way of summarizing the main properties of a class.

Variables: Class Type vs. Primitive Type What does a variable hold? It depends on the type: primitive type or class type. A primitive type variable holds the value of the variable. Class types are more complicated. They have methods and instance variables. A class type variable holds the memory address of the object or a reference to the object. The variable does not actually hold the value of the object. In fact, as stated many times, objects generally do not have a single value. They also have methods, so it does not make sense to talk about an object’s “value”.

Assignment with Variables of Class Type klingon.set("Klingon ox", 10, 15); earth.set("Black rhino", 11, 2); earth = klingon; earth.set("Elephant", 100, 12); System.out.println("earth:"); earth.writeOutput(); System.out.println("klingon:"); klingon.writeOutput(); klingon and earth are two objects of the Species class. What will the output be? (see the next slide)

Assignment with Variables of a Class Type klingon.set("Klingon ox", 10, 15); earth.set("Black rhino", 11, 2); earth = klingon; earth.set("Elephant", 100, 12); System.out.println("earth:"); earth.writeOutput(); System.out.println("klingon:"); klingon.writeOutput(); Output: earth: Name = Elephant Population = 100 Growth Rate = 12% klingon: What will the output be? klingon and earth both print Elephant. Why do they print the same thing? (see the next slide)

Assignment with Variables of a Class Type earth klingon Black rhino 11 2 Klingon ox 10 15 Before the assignment statement, earth and klingon refer to two different objects. Assignment with Variables of a Class Type klingon.set("Klingon ox", 10, 15); earth.set("Black rhino", 11, 2); earth = klingon; earth.set("Elephant", 100, 12); System.out.println("earth:"); earth.writeOutput(); System.out.println("klingon:"); klingon.writeOutput(); earth klingon Klingon ox 10 15 After the assignment statement, earth and klingon refer to the same object. Why do they print the same thing? The assignment statement makes earth and klingon refer to the same object. When earth is changed to "Elephant", klingon is changed also.

Gotcha: Comparing Class Variables A variable of class type contains only the memory address where the object is stored. If two class variables are compared using ==, the addresses, not the values, are compared! This is rarely what you want to do! Use the class’s equals method to compare the actual objects. When writing a class, you should usually include an equals method for comparing objects. Be sure to name it equals.

Example: Comparing Class Variables //User enters first string. String firstLine = keyboard.nextLine(); //User enters second string. String secondLine = keyboard.nextLine(); //This compares their addresses. if(firstLine == secondLine) { <body of if statement> } //This compares their values. if(firstLine.equals(secondLine) { Use equals method (not ==) to compare the actual objects.

Pass the Address: Class Types as Method Parameters In the same way, class variable names used as parameters in a method call copy the argument’s address (not the values) to the formal parameter. So the formal parameter name also contains the address of the argument. It is as if the formal parameter name is an alias for the argument name. Any action taken on the formal parameter is actually taken on the original argument! Unlike the situation with primitive types, the original argument is not protected for class types!

Example: Class Type as a Method Parameter //makeEqual method added to Species class. public void makeEqual(Species otherObject) { otherObject.name = this.name; otherObject.population = this.population; otherObject.growthRate = this.growthRate; } //Method invocation in program using Species class. Species s1 = new Species(); Species s2 = new Species(); s1.set("cat", 25, 5); s2.set("dog", 15, 7); s1.makeEqual(s2);

Example: Class Type as a Method Parameter The method call makes otherObject an alias for s2. The method acts on s2, the Species object passed to the method! After the method is finished, s2 has the same values as s1. That is, both s1 and s2 have the name cat, the population 25, and the growth rate 5. This is unlike primitive types, where the passed variable cannot be changed. See page 288 for another example. To repeat, a method cannot change the value of an argument of primitive type. On the other hand, a method can change the values of an argument of class type.