Chapter 7 Object-Oriented Programming Part 2: User-Defined Classes.

Slides:



Advertisements
Similar presentations
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Advertisements

Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Road Map Introduction to object oriented programming. Classes
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Classes and Objects Systems Programming.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Sub and superclasses using extends
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Class Modifiers So far we have seen many examples of such modifiers E.g. Public Abstract etc.
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
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.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
CSE 1301 Lecture 4 Using Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
1 Chapter 8 – Classes and Object: A Deeper Look Outline 1 Introduction 2 Implementing a Time Abstract Data Type with a Class 3 Class Scope 4 Controlling.
CSE 1301 Lecture 5 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Chapter 7 Object-Oriented Programming Part 2: User-Defined Classes.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Introduction to Java Java Translation Program Structure
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
CSE 1301 Lecture 6 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
OBJECT ORIENTED PROGRAMMING II LECTURE 2_1 GEORGE KOUTSOGIANNAKIS
Chapter 3: Using Methods, Classes, and Objects
Lecture 14 Writing Classes part 2 Richard Gesick.
Lecture 4 Using Classes Richard Gesick.
Lecture 13 Writing Classes Richard Gesick.
Object Based Programming
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 6 Methods: A Deeper Look
Introduction to Classes and Objects
Applying OO Concepts Using Java
Object Oriented Programming in java
Classes and Objects Systems Programming.
Presentation transcript:

Chapter 7 Object-Oriented Programming Part 2: User-Defined Classes

Topics Defining a Class Defining Instance Variables Writing Methods The Object Reference this The toString and equals Methods static Members of a Class Graphical Objects enum Types Creating Packages Documentation Using Javadoc

Why User-Defined Classes? Primitive data types (int, double, char,.. ) are great … … but in the real world, we deal with more complex objects: products, websites, flight records, employees, students,.. Object-oriented programming enables us to manipulate real-world objects.

User-Defined Classes Combine data and the methods that operate on the data Advantages: –The class methods are responsible for the validity of the data. –Implementation details can be hidden. –A class can be reused. Client of a class –A program that instantiates objects and calls the methods of the class

Syntax for Defining a Class accessModifier class ClassName { // class definition goes here } ***Note that the curly braces are required.

Use a noun for the class name. Begin the class name with a capital letter. SOFTWARE ENGINEERING TIP

Important Terminology Fields –instance variables: the data for each object –class data: static data that all objects share Members –fields and methods Access Modifier –determines access rights for the class and its members –defines where the class and its members can be used

Access Modifiers Access ModifierClass or member can be referenced by… publicmethods of the same class and methods of other classes privatemethods of the same class only protectedmethods of the same class, methods of subclasses, and methods of classes in the same package No access modifier (package access) methods in the same package only

public vs. private Classes are usually declared to be public. Instance variables are usually declared to be private. Methods that will be called by the client of the class are usually declared to be public. Methods that will be called only by other methods of the class are usually declared to be private. APIs of methods are published (made known) so that clients will know how to instantiate objects and call the methods of the class.

Defining Instance Variables Syntax: accessModifier dataType identifierList; dataType can be primitive data type or a class type identifierList can contain: –one or more variable names of the same data type –multiple variable names separated by commas –initial values Optionally, instance variables can be declared as final.

Examples of Instance Variable Definitions private String name = ""; private final int PERFECT_SCORE = 100, PASSING_SCORE = 60; private int startX, startY, width, height;

Define instance variables for the data that all objects will have in common. Define instance variables as private so that only the methods of the class will be able to set or change their values. Begin the instance variable identifier with a lowercase letter and capitalize internal words. SOFTWARE ENGINEERING TIP

The Auto Class public class Auto { private String model; private int milesDriven; private double gallonsOfGas; } The Auto class has three instance variables: model, milesDriven, and gallonsOfGas.

Writing Methods Syntax: accessModifier returnType methodName( parameter list ) // method header { // method body } parameter list is a comma-separated list of data types and variable names. –to the client, these are arguments –to the method, these are parameters The parentheses are required even if the method takes no parameters. **Note that the method header is the method’s API.

Use verbs for method names. Begin the method name with a lowercase letter and capitalize internal words. SOFTWARE ENGINEERING TIP

Method Return Types The return type of a method is the data type of the value that the method returns to the caller. The return type can be any of Java's primitive data types, any class type, or void. Methods with a return type of void do not return a value to the caller.

Method Body The code that performs the method's function is written between the beginning and ending curly braces. Unlike if statements and loops, these curly braces are required, regardless of the number of statements in the method body. In the method body, a method can declare variables, call other methods, and use any of the program structures we've discussed, such as if/else statements, while loops, for loops, switch statements, and do/while loops.

main is a Method public static void main( String [] args ) { // application code } Let's look at main's API in detail: public main can be called from outside the class. (The JVM calls main.) static main can be called by the JVM without instantiating an object. void main does not return a value String [] args main's parameter is a String array

Value-Returning Methods Use a return statement to return a value Syntax: return expression; Note: All possible execution paths in the method must return a value. Thus, a method can have multiple return statements.

Constructors Special methods that are called automatically when an object is instantiated using the new keyword. A class can have several constructors. The job of the class constructors is to initialize the instance variables of the new object.

Defining a Constructor Syntax: public ClassName( parameter list ) { // constructor body } Note: constructors have no return value, not even void! Each constructor must have a different number of parameters or parameters of different types. Default constructor: a constructor that takes no arguments. See Examples 7.1 and 7.2, Auto.java and AutoClient.java

Default Initial Values If the constructor does not assign values to the instance variables, they receive default values depending on the instance variable’s data type. Data TypeDefault Value byte, short, int, long0 float, double0.0 charThe null character booleanfalse Any object reference (for example, a String) null

Do not specify a return value for a constructor (not even void). Doing so will cause a compiler error in the client program when the client attempts to instantiate an object of the class. Common Error Trap

Class Scope Instance variables have class scope, meaning that: –A constructor or method of a class can directly refer to instance variables. Methods also have class scope, meaning that: –A constructor or method of a class can call other methods of a class (without using an object reference).

Local Scope A method's parameters have local scope, meaning that: –a method can directly access its parameters. –a method's parameters cannot be accessed by other methods. A method can define variables which also have local scope, meaning that: –a method can access its local variables. –a method's local variables cannot be accessed by other methods.

Summary of Scope A method in a class can access: –the instance variables of its class –any parameters sent to the method –any variables the method declares from the point of declaration until the end of the method or until the end of the block in which the variable is declared, whichever comes first –any methods in the class

Accessor Methods Clients cannot directly access private instance variables, so classes provide public accessor methods with this standard form: public returnType getInstanceVariable( ) { return instanceVariable; } (returnType is the same data type as the instance variable)

Accessor Methods Example: the accessor method for model public String getModel( ) { return model; } See Examples 7.3 Auto.java and 7.4 AutoClient.java

Mutator Methods Mutator methods allow the client to change the values of instance variables. They have this general form: public void setInstanceVariable( dataType newValue ) { // if newValue is valid, // assign newValue to the instance variable }

Mutator Methods Example: the mutator method for milesDriven public void setMilesDriven( int newMilesDriven ) { if ( newMilesDriven >= 0 ) milesDriven = newMilesDriven; else { System.err.println( "Miles driven " + "cannot be negative." ); System.err.println( "Value not changed." ); } See Examples 7.5 Auto.java and 7.6 AutoClient.java

Write the validation code for the instance variable in the mutator method and have the constructor call the mutator method to validate and set initial values. This eliminates duplicate code and makes the program easier to maintain. SOFTWARE ENGINEERING TIP

Do not declare method parameters. Parameters are already defined and are assigned the values sent by the client to the method. Do not give the parameter the same name as an instance variable. The parameter has name precedence so it "hides" the instance variable. Do not declare a local variable with the same name as an instance variable. Local variables have name precedence and hide the instance variable. Common Error Trap

Data Manipulation Methods Perform the "business" of the class. Example: a method to calculate miles per gallon: public double calculateMilesPerGallon( ) { if ( gallonsOfGas != 0.0 ) return milesDriven / gallonsOfGas; else return 0.0; } See Examples 7.7 Auto.java and 7.8 AutoClient.java

The Object Reference this How does a method know which object's data to use? this is an implicit parameter sent to methods. this is an object reference to the object for which the method was called. When a method refers to an instance variable name, this is implied. Thus, variableName is understood to be this.variableName Example: model is understood to be this.model

Using this in a Mutator Method public void setInstanceVariable( dataType instanceVariableName ) { this.instanceVariableName = instanceVariableName; } Example: public void setModel( String model ) { this.model = model; } this.model refers to the instance variable. model refers to the parameter.

The toString Method Returns a String representing the data of an object Clients can call toString explicitly by coding the method call. Clients can call toString implicitly by using an object reference where a String is expected. Example client code: Auto compact = new Auto( ); // instantiate // an object // explicit toString call System.out.println( compact.toString( ) ); // implicit toString call System.out.println( compact );

The toString API Return value Method name and argument list StringtoString( ) returns a String representing the data of an object

Auto Class toString Method public String toString( ) { DecimalFormat gallonsFormat = new DecimalFormat( "#0.0" ); return "Model: " + model + "; miles driven: " + milesDriven + "; gallons of gas: " + gallonsFormat.format( gallonsOfGas ); }

The equals Method Determines if the data in another object is equal to the data in this object. Example client code using Auto references auto1 and auto2: if ( auto1.equals( auto2 ) ) System.out.println( "auto1 equals auto2" ); Return valueMethod name and argument list booleanequals( Object obj ) returns true if the data in the Object obj is the same as in this object; false otherwise.

The instanceof Operator Because the equals method’s parameter is of type Object, we need to determine if the parameter is an Auto object. We can use the instanceof operator to determine if an object reference refers to an object of a particular class. Syntax: objectReference instanceof ClassName evaluates to true if objectReference is of ClassName type; false otherwise.

Auto Class equals Method public boolean equals( Object o ) { // if o is not an Auto object, return false if ( ! ( o instanceof Auto ) ) return false; else { // type cast o to an Auto object Auto objAuto = ( Auto ) o; if ( model.equals( objAuto.model ) && milesDriven == objAuto.milesDriven && Math.abs( gallonsOfGas - objAuto.gallonsOfGas ) < ) return true; else return false; } See Examples 7.10 Auto.java and 7.11 AutoClient.java

static Variables Also called class variables One copy of a static variable is created per class. static variables are not associated with an object. static constants are often declared as public. To define a static variable, include the keyword static in its definition: Syntax: accessSpecifier static dataType variableName…; Example : public static int countAutos = 0;

static Methods Also called class methods Often defined to access and change static variables static methods cannot access instance variables: – static methods are associated with the class, not with any object. –static methods do not have access to the implicit parameter this.

Rules for static and Non-static Methods See Examples 7.12 Auto.java and 7.13 AutoClient.java static Method Non-static Method Access instance variables?noyes Access static class variables?yes Call static class methods?yes Call non-static instance methods? noyes Use the object reference this?noyes

Reusable Graphical Objects In Chapter 4, the applet code and the Astronaut were tightly coupled; we couldn't draw the Astronaut without running the applet. We want to separate the Astronaut from the applet.

The Astronaut Class To separate the Astronaut from the applet, we define an Astronaut class. –The starting x and y values become instance variables, along with a new scaling factor to allow the client to draw Astronauts of different sizes. –We move the code for drawing the Astronaut into a draw method, with this API: public void draw( Graphics g ) The client will call draw from the paint method of the applet, passing the graphics context object.

The Astronaut Client Applet The applet instantiates Astronaut objects in init The init method of an applet is called automatically, once, when the applet starts executing. It is used to perform initialization, such as instantiating objects. The applet calls draw from the paint method for each Astronaut object. See Example 7.14 Astronaut.java, Example 7.15 AstronautClient.java, and Example 7.16 AstronautClient2.java.

enum Types Special class definition designed to increase the readability of code Allows you to define a set of objects that apply names to ordered sets Examples of ordered sets: –Days of the week –Months of the year –Playing cards

enum Types Built into java.lang (no import statement needed) Syntax: enum EnumName { obj1, obj2,… objn }; Example: enum Days { Sun, Mon, Tue, Wed, Thurs, Fri, Sat }; A constant object is instantiated for each name in the list. Thus, each name is a reference to an object of type Days.

Using an enum Object Referring to an enum object reference: Syntax: EnumType.enumObject Example: Days.Mon Declaring an object reference of an enum type Syntax: EnumType referenceName; Example: Days d; // d is initially null d = Days.Thurs;

Useful enum Methods Return valueMethod name and argument list intcompareTo( Enum eObj ) compares two enum objects and returns a negative number if this object is less than the argument, a positive number if this object is greater than the argument, and 0 if the two objects are equal. intordinal( ) returns the numeric value of the enum object. By default, the value of the first object in the list is 0, the value of the second object is 1, and so on.

More Useful enum Methods See Example 7.17 EnumDemo.java Return valueMethod name and argument list booleanequals( Object eObj ) returns true if this object is equal to the argument eObj; returns false otherwise StringtoString( ) returns the name of the enum constant EnumvalueOf( String enumName ) static method that returns the enum object whose name is the same as the String argument enumName

Using enum Objects with switch Using enum objects for case constants makes the code more readable. For the case constant, use the enum object reference without the enum type Example: case Fri: See Example 7.18 DailySpecials.java

Creating Packages A package is a collection of related classes that can be imported into a program. Packages allow reuse of classes without needing to place the class in the same directory/folder as the other source files. To include a class in a package, precede the class definition with the package statement: package packageName;

Naming Packages To avoid name collisions, which can occur when multiple programmers define packages, we use this naming convention: Use the reverse of the domain name, excluding " www ". For example, for a domain name: the package name would begin with: com.jbpub then add the package name: com.jbpub.af

A Reusable Class For example, we can create a class that provides type-safe reading of input from the console that can be reused by our programs. /** Type-Safe Input Using Scanner * Anderson, Franceschi */ package com.jbpub.af; // package name import java.util.Scanner; public class ConsoleIn { // rest of class definition See Example 7.20 ConsoleIn.java

Create the Directory Structure For the package com.jbpub.af, we create three directories. We place ConsoleIn.java into the af directory and compile it.

Modify the CLASSPATH The CLASSPATH environment variable tells the compiler where to look for packages. Set the CLASSPATH to include the directory/folder in which you created the com directory for your package. On Windows, if com is created in My Documents, the CLASSPATH might be:.;c:\documents and settings\user\My Documents On Linux, if com is created in myClasses in your home directory, the CLASSPATH might be:.;/usr/local/java/jre/lib;/home/user/myClasses

Client Use of Package To reuse the classes in a package, the client imports the package. import com.jbpub.af.ConsoleIn; See Example 7.21 ConsoleInClient.java

Javadoc Documentation The Java class library documentation on Oracle's website ( helps us determine how to instantiate objects and call methods for the classes. This documentation was generated using Javadoc, a tool provided in the Java Development Toolkit (JDK). We can also use Javadoc to generate web pages that provide documentation on our class's fields and methods.

To Use Javadoc We need to add Javadoc comments and special tags to our classes. Javadoc comments begin with /** and end with */ (Note that this is similar to a Java block comment, but with an extra * in the opening syntax.) Example: /** Auto class * Anderson, Franceschi */

Block Tags Identify parameters and return values HTML tags can be used in the descriptions –For example, to insert a new line TagCommon syntax variableName description description

Sample equals Method Documentation /** * equals method: * Compares the fields of two Auto objects a1 an Auto object true if this object’s fields have * the same values as a1’s fields; * false, otherwise */ public boolean equals( Object a1 ) { // equals method body }

Executing Javadoc javadoc.exe is located in the bin directory of the Java JDK To generate documentation for a class: javadoc ClassName.java Example: javadoc Auto.java To generate documentation for all classes in a directory: javadoc *.java See Example 7.22 SimplifiedAuto.java

Sample Javadoc Documentation