Chapter 9: Classes with Instance Variables or Classes=Methods+Variables Asserting Java © Rick Mercer.

Slides:



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

IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.
Asserting Java ©Rick Mercer Chapter 3 Objects and JUnit.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Road Map Introduction to object oriented programming. Classes
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
1 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Chapter 3 Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To understand.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Defining Classes and Methods Chapter 4.1. Key Features of Objects An object has identity (it acts as a single whole). An object has state (it has various.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Writing Classes (Chapter 4)
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.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
6-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 Presentation Copyright.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
1 Warm-Up Problem Just like with primitive data types (int, double, etc.), we can create arrays of objects. ex: bankAccount employees[100]; Problem: It’s.
Classes: Member Functions and Implementation November 22, 2002 CSE103 - Penn State University Prepared by Doug Hogan.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Classes Definition A class is a data type whose variables are objects Object – a variable that has member functions as well the ability to hold.
Chapter 4 Introduction to Classes, Objects, Methods and strings
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
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.
24-Dec-15 Class Structure. 2 Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
1 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
OOP Basics Classes & Methods (c) IDMS/SQL News
CS 100Lecture71 CS100J Lecture 7 n Previous Lecture –Computation and computational power –Abstraction –Classes, Objects, and Methods –References and aliases.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 3 Implementing Classes
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Lecture 3 John Woodward.
Implementing Classes Yonglei Tao.
Chapter 4: Writing Classes
Object-Oriented Programming: Classes and Objects
suggested reading: Java Ch. 6
Chapter Three - Implementing Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Chapter 6 Class Definitions and Member Functions
CS100J Lecture 7 Previous Lecture This Lecture Java Constructs
JAVA CLASSES.
Object Oriented Programming in java
Introduction to Object-Oriented Programming
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

Chapter 9: Classes with Instance Variables or Classes=Methods+Variables Asserting Java © Rick Mercer

Classes Classes are ○ a collection of methods and data ○ a blueprint used to construct many objects ○ a great way to partition a software system ○ A way to implement any type A type defines a set of values, and the allowable operations on those values One class constructing three different objects, each with its own set of values (state) Computing Fundamentals, Rick Mercer Franklin, Beedle and Associates,

Putting it All Together in a Class Even though quite different in specific methods and state, virtually all classes have these things in common: -variables store the state of the objects -constructors initialize the state of an object -some messages modify the state of objects -some messages provide access to the state of objects 3

General form of a Class public class class-name { //--instance variables private class-name identifier ; private primitive-type identifier ; // Constructor public class-name ( parameters ) { } //--Methods public return-type method-name-1 ( parameters ) { //... } public return- type method-name-N ( parameters ) { //... } 4

An example class simplified public class BankAccount { //--instance variables private String ID; private double balance; // Constructor to initialize the state public BankAccount(String initID, double initBalance) { ID = initID; balance = initBalance; } // Credit this account by depositAmount public void deposit(double depositAmount) { balance = balance + depositAmount; } // Debit this account by withdrawalAmount public void withdraw(double withdrawalAmount) { balance = balance - withdrawalAmount; } 5

class BankAccount continued previous three modify state, these three access state public String getID() { return ID; } public double getBalance() { return balance; } public String toString( ) { return ID + " $" + balance; } } // End class BankAccount 6

Objects are a lot about Operations and State The methods declared public are the messages that may be sent to any instance of the class the objects The instance variables declared private store the state of the objects ○ private means no direct access from outside the class Every instance of a class has it own separate state ○ If you have 5,234 BankAccount objects, you'll have 5,234 IDs and 5, 234 balances. 7

The Unified Modeling Language (UML) class diagram -- another view of a class methods and state 8

Sample Messages BankAccount anAcct = new BankAccount("Moss", ); anAcct.withdraw(60); anAcct.deposit(147.35); // These assertions should pass assertEquals("Moss", anAcct.getID()); assertEquals(500.0, anAcct.getBalance(), 0.001); 9

Instance Variables State of objects stored as instance variables ○ these are the variables that are declared inside the class, but outside of the method bodies ○ each instance of the class (object) has its own values stores in its own instance variables with 954 objects you have 954 sets of instance variables ○ all methods in the class can access instance variables and most methods will reference at least one of the instance variables the data and methods are related ○ when declared private, no one else can access the instance variables the state is encapsulated, nice and safe behind methods 10

Constructors Constructor ○ a special method that initializes the state of objects ○ gets invoked when you construct an object ○ has the same name as the class ○ does not have a return type a constructor returns a reference to the instance of the class Assigning object references to reference variables String aString = new String("Initial state"); BankAccount anAcct = new BankAccount("Katey", 10.00); JFrame window = new JFrame("My Application"); 11

Constructors General form: calling a constructor to construct and initialize an object class-name object-name = new class-name ( initial-state ); ○ class-name: name of the class ○ object-name: any valid Java identifier ○ initial-state: zero or more arguments supplied during instance creation. 12

Constructors A constructor uses the arguments initial-state to help initialize the private instance variables public BankAccount(String initID, double initBalance) { ID = initID; balance = initBalance; } BankAccount anAcct = new BankAccount("Kellen", ); 13

Methods that Access State Other methods return the current value of an object's data member, or return some information related to the state of an object anAccount.getBalance()// return current balance aString.substring(0, 3) // Get part of a string Some accessing methods simply return values of instance variables, others require some processing 14

return in non-void methods Java's return statement provide the means to return information, General form return expression ; When return executes, the value of expression replaces the message control returns to the message expression must match the return type of method heading ○ String return type means you must return a String ○ double return type? Return a double You can not return an value from a void method 15

Returning Information public String getID() { return ID; } public double getBalance() { return balance; } System.out.println( + anAcct.getID() + ": " + anAcct.getBalance()); Output: Kellen An instance of BankAccount 16

Implementing Methods that Modify State Some methods modify (change) the state of an object: anAccount.withdraw(120.00) // Account balance has been reduced by // Modify the state of any BankAccount object public void withdraw(double amount) { // balance is an instance variable balance = balance + amount; } 17

Naming Conventions Rules #1, 2, and 3: 1: Always use meaningful names 2: Always use meaningful names 3: Always use meaningful names Rule #4 Constructors: Same name as the class 18

public or private? When designing a class, do this at least for now ○ declare constructors and methods public ○ declare instance variables private Public messages can be sent from wherever the object is in scope Private state can not be messed up like this BankAccount myAcct = new BankAccount("Me", 10.00); myAcct.balance = myAcct.balance ; 19

Protecting an Object's State  Access modes make operations available to clients and also protect the state  Instance variables and methods are known as follows Access ModeWhere is the symbol known? Access ModeWhere is the symbol known? public From all methods of the class and in the scope public From all methods of the class and in the scope (where it is known) of the object private Known only in the class private Known only in the class 20

Some Guidelines Recommendations for writing your first classes: ○ declare instance variables private after class definition ○ declare constructors public no return type, no static! ○ declare most methods public no static! however, private helper methods are often useful ○ look at examples in Book and on the Code Demos page as patterns use one file to store the class (no main method) use a unit test to test instances of the class 21

Object-Oriented Design Guidelines Object-oriented design guideline ○ a rule of thumb intended to help produce good object- oriented software Example: When deciding what access users of a class should have to methods and instance variables OOD Guideline All data should be hidden within its class Translation: make instance variables private 22

Why private? If balance were public, what is it after this? myAcct.balance = myAcct.balance - myAcct.balance; With balance private, compiletime error occurs You want programmers to use the methods ○ imagine the other things that occur during a real withdraw write a transaction to a file check for trying to withdraw more than balance Also, you can later change the class Also, programmers only need to know the methods 23

Cohesion within a class The methods of a class should be strongly related ○ don't put a blastOff method in BankAccount The instance variables should be strongly related ○ don't put double acceleration in BankAccount Cohesion means solidarity, hanging together Classes with high cohesion are a better design ○ the methods and data are related OOD Guideline Keep related data and behavior in one place 24