More About Classes: Instance Methods. Chapter 6

Similar documents
Computing Concepts with Java Essentials

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

AP Computer Science Java Subset

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

Introduction to Java Applets (Deitel chapter 3)

How To Program In Java (Ipt) With A Bean And An Animated Object In A Powerpoint (For A Powerbook)

Java CPD (I) Frans Coenen Department of Computer Science

Problem Solving. Software Engineering. Behavior. OCD in a Nutshell. Behavior. Objects Operations Algorithm. Object-Centered Design

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Assignment # 2: Design Patterns and GUIs

C++ INTERVIEW QUESTIONS

J a v a Quiz (Unit 3, Test 0 Practice)

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

Java Application Developer Certificate Program Competencies

CS 111 Classes I 1. Software Organization View to this point:

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Computer Programming I

Database Programming with PL/SQL: Learning Objectives

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

Going Interactive: Combining Ad-Hoc and Regression Testing

Fundamentals of Java Programming

PROG0101 Fundamentals of Programming PROG0101 FUNDAMENTALS OF PROGRAMMING. Chapter 3 Algorithms

Chapter 1 Java Program Design and Development

How To Write A Program For The Web In Java (Java)

Java (12 Weeks) Introduction to Java Programming Language

Inside the Java Virtual Machine

Moving from CS 61A Scheme to CS 61B Java

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CS506 Web Design and Development Solved Online Quiz No. 01

Glossary of Object Oriented Terms

Java Interview Questions and Answers

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Sources: On the Web: Slides will be available on:

6.1. Example: A Tip Calculator 6-1

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

The C Programming Language course syllabus associate level

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Chapter 13 - Inheritance

Description of Class Mutation Mutation Operators for Java

Part 1 Foundations of object orientation

13 Classes & Objects with Constructors/Destructors

Contents. 9-1 Copyright (c) N. Afshartous

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Software Engineering Techniques

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

Java Basics: Data Types, Variables, and Loops

History OOP languages Year Language 1967 Simula Smalltalk

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

AP Computer Science A - Syllabus Overview of AP Computer Science A Computer Facilities

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Part I. Multiple Choice Questions (2 points each):

D06 PROGRAMMING with JAVA

Syllabus for CS 134 Java Programming

CSC384 Intro to Artificial Intelligence

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Introduction to programming

Lecture 5: Java Fundamentals III

Chapter 1 Fundamentals of Java Programming

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Part 3: GridWorld Classes and Interfaces

More on Objects and Classes

El Dorado Union High School District Educational Services

Crash Course in Java

TATJA: A Test Automation Tool for Java Applets

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Introduction to Object-Oriented Programming

How Scala Improved Our Java

Many applications consist of one or more classes, each containing one or more methods. If you become part of a development team in industry, you may

Variable Base Interface

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Install Java Development Kit (JDK) 1.8

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Chapter 5 Names, Bindings, Type Checking, and Scopes

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

LAB4 Making Classes and Objects

Guide to Performance and Tuning: Query Performance and Sampled Selectivity

CS170 Lab 11 Abstract Data Types & Objects

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Introduction to Programming System Design. CSCI 455x (4 Units)

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Computer Programming I

Mouse Event Handling (cont.)

CS 106 Introduction to Computer Science I

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

1001ICT Introduction To Programming Lecture Notes

Course Title: Software Development

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

To Java SE 8, and Beyond (Plan B)

Java Classes. GEEN163 Introduction to Computer Programming

CS193j, Stanford Handout #4. Java 2

C# and Other Languages

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Object Oriented Software Design II

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Transcription:

More About Classes: Instance Methods Chapter 6

Chapter Contents Chapter Objectives 6.1 Introductory Example: Modeling Temperatures 6.2 Designing a Class 6.3 Implementing Class Attributes 6.4 Implementing Class Operations 6.5 Graphical/Internet Java: Raise the Flag

Chapter Objectives Look at how to build classes as types Study instance methods contrast with static (class) methods Place in context of real world object (temperature) Implement attribute (instance) variables Explain importance of encapsulation and information hiding

Chapter Objectives Build a complete class to model temperatures Describe, give examples for constructors, accessor methods, mutator methods, converter methods, utility methods Investigate graphics programming Look at artificial intelligence topics

Classes Generally used to describe a group or category of objects attributes in common Java class used as a repository for static methods used by other classes Now we will create a class that serves as a type from which objects are created contains instance methods

6.1 Introductory Example: Modeling Temperatures Problem Temperature Conversion Fahrenheit, Celsius, Kelvin Preliminary Analysis Attributes of temperature number of degrees scale We seek a type which will hold all attributes and provide methods for manipulating those attributes

Object-Centered Design Objects Type Kind Name program screen Screen varying thescreen prompt String constant temperature Temperature varying temp keyboard Keyboard varying thekeyboard Fahrenheit equivalent Temperature varying Celsius equivalent Temperature varying Kelvin equivalent Temperature varying

Operations Display a string on thescreen Read a Temperature from thekeybard Determine Fahrenheit equivalent of Temperature Determine Celsius equivalent Determine Kelvin equivalent Display a Temperature on thescreen

Algorithm 1. Declare thescreen, thekeyboard, temp 2. Send thescreen message to display prompt 3. Send temp a message, ask it to read value from thekeyboard 4. Send thescreen a message to display Fahrenheit, Celsius, Kelvin equivalents

Coding Note source code, Figure 6.2 in text Assumes existence of the class Temperature Note calls to Temperature methods.read(thekeyboard).infahrenheit().incelsius().inkelvin

6.2 Designing a Class For a class, we must identify Behavior, operations applied to class objects Attributes, data stored to characterize a class object These are wrapped together in a class declaration

Class Declaration Syntax: class classname { Method definitions Field Declarations } Method definitions are as described in earlier chapters Field declarations are of variables and constants

External and Internal Perspectives External Perspective observer from outside the program views internal details Internal Perspective object carries within itself ability to perform its operations object autonomy

Temperature Behavior Define myself implicitly initialize degrees, scale with default values Read value from a Keyboard object and store it within me Compute Fahrenheit, Celsius, Kelvin temperature equivalent to me Display my degrees and scale using a Screen object

Additional Behaviors Desired Define myself explicitly with degrees, scale Identify my number of degrees Identify my scale Increase, decrease my degrees by a specified number Compare myself to another Temperature object Assign another Temperature value to me

Temperature Attributes Review the operations Note information each requires Temperature has two attributes 1. my degrees 2. my scale

Implementing Class Attributes Stand alone class declared in a separate file: Temperature.java Specify variables to hold the attributes double mydegrees; char myscale; called the instance variables, data members, or fields

Encapsulation Wrap the attribute objects in a class declaration class Temperature { } double mydegrees; char myscale; The class Temperature encapsulates mydegrees and myscale Use the class declaration as a type for declare actual objects Temperature todaystemp = new Temperature();

Information Hiding Attribute variables can be accessed directly todaystemp.myscale = 'Q'; //??? We wish to ensure valid values only Solution is to hide the information to direct outside access class Temperature { private double mydegrees; private char myscale; } It is good programming practice to hide all attribute variables of a class by specifying them as private

Class Invariants Important to identify restrictions on values of attributes minimum, maximum temp myscale limited to F, C, or K Specify with boolean statements in comments... private char myscale; // 'F', 'C', or 'K'

Class Invariants Helpful to specify static (class) constants class Temperature { All objects of type Temperature share a single instance of these values public final static double ABS_ZERO_F = -459.67; ABS_ZERO_C = -273.15; ABS_ZERO_K = 0.0;

6.4 Implementing Static Operations Use instance methods Contrast: Static (Class) Methods Declared with keyword static Shared by all objects of class Invoke by sending message to the class Instance (Object) Methods No static modifier used Each class has its own copy Invoked by sending message to class object

Instance Methods Categories Constructors initialize attribute variables Accessors retrieve (but not change) attribute variables Mutators change attribute variable values Converters provide representation of an object in a different type Utilities used by other methods to simplify coding

Temperature Output: a Convert-to-String Method print() and println() methods used display a value whose type is Object or any class that extends Object send object message to convert itself to String using tostring() (a converter) Thus thescreen.print(todaystemp) asks todaystemp to return a String representation of itself Note source code Figure 6.3 in text

Constructor Methods Temperature temp1 = new Temperature Initial values for mydegree and myscale are 0 and NULL, respectively Better to give them valid values Constructor method used to give these values default-value constructor explicit value constructor

Default Value Constructor Whenever a Temperature object is declared, this specifies initial values public Temperature() { mydegrees = 0.0; myscale = 'C'; } Note: no return type (not even void) name of constructor method must be same as name of class

Explicit-Value Constructors Useful to initialize values at declaration time Explicit value constructor uses parameters to initialize mydegrees and myscale Note source code Figure 6.5 in text Constructor invoked by Temperature todaystemp = new Temperature(75,'F');

Method Names and Overloading Now we have two methods with the same name but different numbers of parameters Two or more methods with same name called overloading compiler determines which method to use based on number and/or types of arguments in call

Utility Methods Class Temperature methods need check for validity of incoming or changing values of variables mydegrees must be greater than absolute zero myscale must be one of 'C', 'K', or 'F' Utility method provided isvalidtemperature()

A Utility Method: fatal() isvalidtemperature() handles only the incoming parameters not the attribute variables If they are wrong the fatal() method is called (note source code Figure 6.7) displays diagnostic message method where problem detected description of problem terminates execution

Static vs. Instance Methods Note that tostring() and the constructor methods are instance methods isvalidtemperature() and fatal() are static methods Instance method: invoked by message sent to instance of a class Static method: invoked by message sent to the class itself

Static vs. Instance Methods Static methods may only access static variables, constants, and static methods access only static declared items Instance methods may access both instance and static variables, constants, methods Objects have their own distinct copies of instance variables, constants, methods Objects share the same copy of static variables, constants, methods

Class Design Pointers Most variables should be declared as attribute variables If a method needs to access attribute variables then define it as a instance method If a method does not need to access static variables make it a static (class) method pass information to it via parameters or declared class attributes

Accessor Methods Methods that allow program to retrieve but not modify class attributes Example: public double getdegrees() { return mydegrees; }

Mutator Methods Input into a Temperature object Desired command: todaystemp.read(thekeyboard); reads a number, a character from keyboard stores them in proper variables This is a method that changes values of attribute variables thus called a mutator

Managing the Input Need for strategy to handle invalid inputs from user will return boolean value to indicate validity of inputs Note the source code, Figure 6.9 of text observe differences from constructor values come from thekeyboard instead of parameters returns boolean value instead of generating fatal error

Conversion Methods A temperature object should be able to compute any scale equivalent of itself method returns appropriate value based on current value of myscale Note source code, Figure 6.10 result initialized to null method constructs a Temperature value for result return statement makes result value returned

Raising/Lowering a Temperature We need a method which enables the following command tuestemp = montemp.raise(4.5); // or.lower() The return value would be an object of the same scale, different mydegrees Method should use isvalidtemperature() to verify results if invalid results, uses the fatal() utility Note source code Figure 6.11

Comparing Temperature Values We cannot use if (montemp < tuestemp) We must use something like if montemp.lessthan(tuestemp) View source code Figure 6.12, note: must convert to proper scale for comparison then simply return results of comparison of mydegrees with the results of parameter's getdegrees() method Similar strategy for the.equals() method

Alternate Comparison Strategy Note the duplicate code in the.lessthan() and.equals() methods Write a single method.compareto() which returns 1, 0, or +1 signifying <, ==, or > Rewrite.lessThan() and.equals() to call the.compareto() and decide the equality/inequality based on 1, 0, or +1

Reference-type Declaration Reference is another word for address Temperature temp = new Temperature(37,'C'); The variable temp really holds the address for the memory location allocated by the new command temp mydegrees myscale 37 C

Handles temp is the only way to access the Temperature object it has no name of its own temp is the handle for the object it references temp mydegrees myscale 37 C

Reference Type Copying Consider the following two statements: Temperature temp = new Temperature(37,'C'); Temperature temp2 = temp; Note: declaration of temp2 did not use the new command a new object did not get created we merely have two handles for one object temp temp2 mydegrees myscale 37 C

Reference Type Copying At times we need to create another object, not just another pointer create a copy method returns a distinct Temperature object, equal to (a clone of) itself public Temperature copy() { return new Temperature(myDegrees,myScale); } Invoked as shown: Temperature newtemp = oldtemp.copy();

Reference Type Copying Note simplicity of this copy method all attribute variables happen to be primitive types If attribute variables were, themselves, reference types our version would make only handles to the actual attribute variable objects this called shallow copy For truly distinct, deep copy each reference type attribute variable must be copied separately

Class Organization Note source code of entire class, Figure 6.17 Standard practice begin class with constants class provides follow with constructors, accessors, mutators, converters, utilities place attribute variable declarations last

Class Interface Benefits of private attribute variables forces programs to interact with class object through its public methods public operations thought of as the "interface" Design the interface carefully gives stability to the class even though implementation of methods changes, use of the class remains unchanged

6.5 Graphical/Internet Java: Raise the Flag A ClosableFrame Class provided in ann.gui package we will build classes that extend this class class DrawingDemo extends ClosableFrame { public static void main(string [] args) { DrawingDemo mygui = new DrawingDemo(); mygui.setvisible(true); } } Sends the new object a message to make itself visible Creates a new instance

Inheritance DrawingDemo class inherits all attributes of CloseableFrame variables and constants behaviors (methods) Sample methods of CloseableFrame set the frame title set colors set size access width, height set visibility

Painting Top-level containers contain intermediate containers called panes or panels Content pane is most important used to group, position components Note source code, Figure 6.18 in text main method now also creates a DrawingPane and specifies the size

Methods in DrawingPain() Use subclasses of JPanel constructor sets background to white paintcomponent() painting of Swing components must be performed by a method with this name This is where statements that do the actual painting reside public void paintcomponent(graphics pen) { /* statements to do painting */ }

Graphics Class Methods Sample graphics methods drawarc drawline drawoval drawstring This is a string

Dutch Flag GUI Application Note source code Figure 6.19 Uses the paintcomponent() method draws two rectangles red filled on top blue filled on bottom middle stripe is original white background

Dutch Flag Applet Source code Figure 6.20 Many Swing components used in both applets and applications Modifications: This class extends JApplet instead of CloseableFrame change main method to init()

Part of the Picture: Artificial Intelligence Recently (5/97) a computer program defeated a world chess champion Construction of game playing programs is known as artificial intelligence or AI for short Definition of AI is difficult intelligent behavior is complex styles of programming AI are diverse

Intelligence A chess playing program is intelligent in a very narrow domain General human intelligence is demonstrated in a wide range of behaviors

AI Topics Reasoning and problem solving Memory of things in our world Motion and manipulation of objects (robotics) Perception computer vision, speech recognition Language processing understanding and generation translation Learning from past experiences Which of these can the chess playing computer do?

AI Programming Techniques Heuristic search search through choices and consequences Logic programming represent knowledge in well defined format perform logic inferences on it

AI Programming Techniques Expert systems encode knowledge from an expert in some domain Neural networks model the way the brain works use highly interconnected simple processes

Example: JackDice Game Similar to blackjack Roll two dice, sum the values Continue rolling as desired Come as close to 21 without going over Simulate this intelligent activity with a Java program see driver program, Figure 6.21

Strategies for JackDice Scaled-down expert system encode knowledge from expert players Examples of expert knowledge always accept the first roll (never risks passing 21) randomly decide whether to go on or not (???) take more risks if you are behind in a game play conservative if you are ahead