More About Objects and Methods

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Advertisements

Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Road Map Introduction to object oriented programming. Classes
Chapter 51 Feb 08, Chapter 52  Methods in a class are invoked using objects A a1 = new A(); a1.func1();  Calling object and the dot can be omitted.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 3: Parameters, Return, and Interactive Programs with Scanner.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Classes, Objects, and Methods
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Introduction To Scientific Programming Chapter 5 – More About Objects and Methods.
Java Classes Appendix C © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Chapter 6: Functions Starting Out with C++ Early Objects
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
More About Objects and Methods Chapter 5. When an Object Is Required Methods called outside the object definition require an object to precede the method.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Lecturer: Dr. AJ Bieszczad Chapter 5 COMP 150: Introduction to Object-Oriented Programming 5-1 l Programming with Methods l Static Methods and Static Variables.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
CPS120: Introduction to Computer Science Functions.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
CSC 142 Computer Science II Zhen Jiang West Chester University
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Polymorphism l Constructors.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
OOP Basics Classes & Methods (c) IDMS/SQL News
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
More About Objects and Methods
Chapter 5: Enhancing Classes
Chapter 7 User-Defined Methods.
Java Programming: Guided Learning with Early Objects
Java Primer 1: Types, Classes and Operators
More About Objects and Methods
Introduction to Object-Oriented Concept
Chapter 3: Using Methods, Classes, and Objects
Chapter 4: Writing Classes
Static and non-Static Chapter 5.
CMSC 202 Static Methods.
CSC240 Computer Science III
Classes, Objects, and Methods
Chapter 6 Methods: A Deeper Look
Java Classes and Objects 3rd Lecture
More About Objects and Methods
More About Objects and Methods
Object Oriented Programming in java
Java Programming Language
Classes, Objects and Methods
More About Objects and Methods Chapter 5 Programming with Methods
More About Objects and Methods Chapter 5 Programming with Methods
Presentation transcript:

More About Objects and Methods Chapter 5 More About Objects and Methods Programming with Methods Static Methods and Static Variables Designing Methods Polymorphism Constructors Information Hiding Revisited Packages

The "this." Operator this. refers to the object that contains the reference Methods called in an object definition file do not need to reference itself You may either use "this.", or omit it, since it is presumed For example, if answerOne() is a method defined in the class Oracle: public class Oracle { ... //One way to invoke the answerOne method defined //in this file: this.answerOne(); //Another way is to omit "this." answerOne(); //"this." is presumed }

When an Object Is Required Methods called outside the object definition require an object to precede the method name For example: Oracle myOracle = new Oracle(); //myOracle is not part of the definition code //for Oracle ... //dialog is a method defined in Oracle class myOracle.dialog();

Static Methods (or class method) Some methods do work but do not need an object For example, methods to calculate area: just pass the required parameters and return the area Use the class name instead of an object name to invoke them For example CircleFirstTry is a class with methods to perform calculations on circles: CircleFirstTry.area(myRadius); Notice that the the method invocation uses "className." instead of " circleObject." Also called class methods

Static Methods Declare static methods with the static modifier, for example: public static double area(double radius) ... Since a static method doesn’t need a calling object, it cannot refer to a (nonstatic) instance variable of the class. Likewise, a static method cannot call a nonstatic method of the class using the implicit this. operator (unless it creates an object of the class to use as a calling object).

Uses for Static Methods Static methods are commonly used to provide libraries of useful and related functions Examples: the Math class automatically provided with Java functions include pow, sqrt, max, min, etc. see the next slide for more details SavitchIn defines methods for keyboard input not automatically provided with Java functions include readLineInt, readLineDouble, etc. see the appendix

The Math Class Includes constants Math.PI ( 3.14159) and Math.E (base of natural logarithms  2.72) Includes three similar static methods: round, floor, and ceil All return whole numbers of type double Math.round returns the whole number nearest its argument : Math.round(3.3)= 3.0 and Math.round(3.7)=4.0;Math.round(-3.5)=-3.0 Math.floor(x) = x Math.floor(3.3)= Math.floor(3.7) = 3.0 Math.ceil(x) = x Math.ceil(3.3)= 4; Math.ceil(-3.7)=-3.0

Static Variables (or class Variables) The StaticDemo program in the text uses a static variable: private static int numberOfInvocations = 0; Similar to definition of a named constant, which is a special case of static variables. May be public or private but are usually private for the same reasons instance variables are. Only one copy of a static variable and it can be accessed by any object of the class. May be initialized (as in example above) or not. Can be used to let objects of the same class coordinate. Not used in the rest of the text.

Wrapper Classes Used to wrap primitive types in a class structure All primitive types have an equivalent class The class includes useful constants and static methods, including one to convert back to the primitive type

Wrapper class example: Integer Declare an Integer class variable: Integer n = new Integer(); Convert the value of an Integer variable to its primitive type, int: int i = n.intValue();//intValue returns an int Some useful Integer constants: Integer.MAX_VALUE - the maximum integer value the computer can represent Integer.MIN_VALUE - the smallest integer value the computer can represent

Wrapper class example: Integer Some useful Integer methods: Integer.valueOf("123") to convert a string of numerals to an integer Integer.toString(123) to convert an Integer to a String The other wrapper classes have similar constants and functions See the text for useful methods for the class Character

Usage of wrapper classes There are some important differences in the code to use wrapper classes and that for the primitive types Wrapper Class variables contain the address of the value variable declaration example: Integer n = new Integer(); variable declaration & init: Integer n = new Integer(0); assignment: n = new Integer(5); Primitive Type variables contain the value variable declaration example: int n; variable declaration & init.: int n = 0; assignment: n = 99;

Designing Methods: Top-Down Design In pseudocode, write a list of subtasks that the method must do. If you can easily write Java statements for a subtask, you are finished with that subtask. If you cannot easily write Java statements for a subtask, treat it as a new problem and break it up into a list of subtasks. Eventually, all of the subtasks will be small enough to easily design and code. Solutions to subtasks might be implemented as private helper methods. Top-down design is also known as divide-and-conquer or stepwise refinement.

Programming Tips for Writing Methods Apply the principle of encapsulation and detail hiding by using the public and private modifiers judiciously If the user will need the method, make it part of the interface by declaring it public If the method is used only within the class definition (a helper method, then declare it private Create a main method with diagnostic (test) code within a class's definition run just the class to execute the diagnostic program when the class is used by another program the class's main is ignored

driver program should have only one untested method Testing a Method Test programs are sometimes called driver programs Keep it simple: test only one new method at a time driver program should have only one untested method If method A uses method B, there are two approaches: Bottom up test method B fully before testing A Top down test method A and use a stub for method B A stub is a method that stands in for the final version and does little actual work. It usually does something as trivial as printing a message or returning a fixed value. The idea is to have it so simple you are nearly certain it will work.

Overloading The same method name has more than one definition within the same class Each definition must have a different signature different argument types, a different number of arguments, or a different ordering of argument types The return type is not part of the signature and cannot be used to distinguish between two methods with the same name and parameter types

Signature the combination of method name and number and types of arguments, in order equals(Species) has a different signature than equals(String) same method name, different argument types myMethod(1) has a different signature than myMethod(1, 2) same method name, different number of arguments myMethod(10, 1.2) has a different signature than myMethod(1.2, 10) same method name and number of arguments, but different order of argument types

Gotcha: Overloading and Argument Type Accidentally using the wrong datatype as an argument can invoke a different method For example, see the Pet class in the text set(int) sets the pet's age set(double) sets the pet's weight You want to set the pet's weight to 6 pounds: set(6.0) works as you want because the argument is type double set(6) will set the age to 6, not the weight, since the argument is type int

Gotcha: Automatic Type Conversion and Overloading If Java does not find a signature match, it attempts some automatic type conversions, e.g. int to double An unwanted version of the method may execute In the text Pet example of overloading: What you want: name "Cha Cha", weight 2, and age 3 But you make two mistakes: set(String,int,double) 1. you reverse the age and weight numbers, and 2. you fail to make the weight a type double. set("Cha Cha", 2, 3) does not do what you want it sets the pet's age = 2 and the weight = 3.0 Why? set has no definition with the argument types String, int, int However, it does have a definition with String, int, double, so it promotes the last number, 3, to 3.0 and executes the method with that signature

Constructors A constructor is a special method designed to initialize instance variables Automatically called when an object is created using new Has the same name as the class Often overloaded (more than one constructor for the same class definition) different versions to initialize all, some, or none of the instance variables each constructor has a different signature (a different number or sequence of argument types)

Defining Constructors Constructor headings do not include the word void In fact, constructor headings do not include a return type A constructor with no parameters is called a default constructor If no constructor is provided Java automatically creates a default constructor If any constructor is provided, then no constructors are created automatically Programming Tip Include a constructor that initializes all instance variables Include a constructor that has no parameters include your own default constructor

Constructor Example from PetRecord public class PetRecord { private String name; private int age; //in years private double weight; //in pounds . . . public PetRecord(String initialName) name = initialName; age = 0; weight = 0; } Initializes three instance variables: name from the parameter and age and weight with default initial values. Sample use: PetRecord pet1 = new Pet(“Eric”);

Using Constructors Always use a constructor after new For example, using the Pet class in text: Pet myCat = new Pet("Calvin", 5, 10.5); this calls the Pet constructor with String, int, double parameters If you want to change values of instance variables after you have created an object, you must use other methods for the object you cannot call a constructor for an object after it is created set methods should be provided for this purpose

Information Hiding Revisited Using instance variables of a class type takes special care The details are beyond the scope of this text, but the problem is described in section 5.6/page360 (see CadetClass.java and Haker.java) Appendix 9 covers some of the details The problem stems from the fact that, unlike primitive types, object identifiers contain the object's address, not its value returning an object gives back the address, so the called method has direct access to the calling object the calling object is "unprotected" (usually undesirable) best solution: cloning, but that is beyond the scope of this book One solution: stick to returning primitive types (int, char, double, boolean, etc.) or String

Packages A way of grouping and naming a collection of related classes they serve as a library of classes they do not have to be in the same directory as your program The first line of each class in the package must be the keyword package followed by the name of the package: package mystuff.utilities; To use classes from a package in a program put an import statement at the start of the file: import mystuff.utilities.*; note the ".*" notation

Package Naming Conventions Use lowercase The package name is the directory pathname with subdirectory separators ("\" or "/", depending on your system) replaced by dots For example, if the package is in a directory named "utilities" in parent directory "mystuff", the package name is: mystuff.utilities

Package Naming Conventions Pathnames are usually relative and use the CLASSPATH environment variable For example, if: CLASSPATH=c:\jdk\lib, and your package utilities is in directory c:\jdk\lib\mystuff\utilities, then you would use MyClass (if imported) or mystuff.utilities.MyClass the system would look in directory c:\jdk\lib\mystuff\utilities to find the file MyClass.class for class MyClass

Summary A method definition can use a call to another method of the same class static methods can be invoked using the class name or an object name Top-down design method simplifies program development by breaking a task into smaller pieces Test every method in a program in which it is the only untested method

Summary Each primitive type has a corresponding wrapper class Overloading: a method has more than one definition in the same class (but the number of arguments or the sequence of their data types is different) one form of polymorphism Constructor: a method called when an object is created (using new) default constructor: a constructor with no parameters