Classes and Objects CMSC 202. Version 9/122 Programming & Abstraction All programming languages provide some form of abstraction. – Also called information.

Slides:



Advertisements
Similar presentations
1 User-Defined Classes The String class is a pre-defined class that is provided by the Java Designer. Sometimes programmers would like to create their.
Advertisements

Control Structures Ranga Rodrigo. Control Structures in Brief C++ or JavaEiffel if-elseif-elseif-else-end caseinspect for, while, do-whilefrom-until-loop-end.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
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.
CMSC 202 Fall 2010, Advanced Section Designing with Objects.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
The Java Programming Language  Simple – but abstract  Safe  Platform-independent ("write once, run anywhere")  Has a Rich growing library  Designed.
CHAPTER 2 OBJECTS AND CLASSES Goals: To understand the concepts of classes and objects To realize the difference between objects and object references.
ECE122 L6: Problem Definition and Implementation February 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation.
Chapter 3 Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To understand.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
Programming Languages and Paradigms Object-Oriented Programming.
Writing Classes (Chapter 4)
Java Language and SW Dev’t
Introduction to Object-Oriented Programming
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Creating Simple Classes. Outline of Class Account Class Account Account # Balance Holder name phone# Overdrawn (true/false) Data Members Open Credit Debit.
Introduction to Java and Object-Oriented Programming AJSS Computer Camp Department of Information Systems and Computer Science Ateneo de Manila University.
Writing JavaDocs Mimi Opkins CECS 274 Copyright (c) Pearson All rights reserved.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Classes CS 21a: Introduction to Computing I First Semester,
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
CS61B L03 Building Objects (1)Garcia / Yelick Fall 2003 © UCB  Dan Garcia ( Kathy Yelick  (
Chapter 4: A Paradigm Program structure Connecting to the Java world Types Access modifiers Lifetime modifiers.
P Chapter 2 introduces Object Oriented Programming. p OOP is a relatively new approach to programming which supports the creation of new data types and.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Introduction to Java Java Translation Program Structure
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Getting Started with Java: Object declaration and creation Primitive.
CMSC 202 CMSC 202, Advanced Section Classes and Objects In Java.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
C# Programming Methods.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Week 13 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
CMSC 202 Classes and Objects. Aug 6, Programming Languages All programming languages provide some form of abstraction Procedural language (eg C)
Chapter 3 Implementing Classes
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Introduction CMSC 202 Fall Instructors Mr. Ryan Bergeron – Lecture Section 01 Tues/Thu 1:00 – 2:15 am, Sondheim 111 – Lecture Section 04 Tues/Thu.
Defining Classes and Methods
More Sophisticated Behavior
Lecture 3 John Woodward.
Classes & Objects CMSC 202.
Introduction to Objects
Object-Oriented Programming: Classes and Objects
Chapter Three - Implementing Classes
Object Based Programming
Defining Your Own Classes Part 1
Defining Classes and Methods
Introduction to Computer Science and Object-Oriented Programming
Defining Classes and Methods
CS100J Lecture 7 Previous Lecture This Lecture Java Constructs
JAVA CLASSES.
Defining Classes and Methods
AN INTRODUCTION TO OBJECTS AND CLASSES
Classes CS 21a: Introduction to Computing I
Introduction to Object-Oriented Programming
In this class, we will cover:
Chap 2. Identifiers, Keywords, and Types
Chapter 9 Introduction To Classes
Introduction to Computer Science and Object-Oriented Programming
Introduction to Objects
Presentation transcript:

Classes and Objects CMSC 202

Version 9/122 Programming & Abstraction All programming languages provide some form of abstraction. – Also called information hiding – Separates code use from code implementation Procedural Programming – Data Abstraction: using data structures – Control Abstraction: using functions Object Oriented Programming – Data and Control Abstraction: using classes

Classes

Recall... Class – A complex data type containing: Attributes – make up the objects state Operations – define the objects behaviors 4 Operations (behaviors) Type Attributes (state) String sequence of characters more? compute length concatenate test for equality more? Bank Account account number owners name balance interest rate more? deposit money withdraw money check balance transfer money more? Version 9/12

Anatomy of a Java Class Access modifier (more on this later) Name of the class Keyword class publicclass BankAccount { } Class body: data members (instance variables), methods NO semi-colon 5Version 9/12

Simple Sample Class public class BankAccount { public String accountNumber;// instance variable public double balance;// instance variable public void deposit(double amount){// method balance += amount; } public double checkBalance( ){// method return balance; } Version 9/126

7 Anatomy of an Instance Variable privatefloatbalance; Optional access modifier (more on this later) Data member type Data member type Data member name Data member name

Version 9/128 Anatomy of a Method Optional access modifier (More on this later) Name of method Name of method return type (may be void) return type (may be void) public float checkBalance { } Method code: local variables and statements () Optional parameters Optional parameters

Packages and Classes Version 9/129 Class 1 Class 2 Class n Package Notes: All code must be inside of a class. Each class is a separate file. The class file name must be the same as the class name, with the.java prefix. All classes must be part of a package (with the exception of a single-class program). The package name must be specified at the top of each class file. A package is a directory, not a file.

Sample Package with Two Classes Version 9/1210 bankProgram package bankProgram; public class BankAccount { // instance vars and methods } package bankProgram; public class BankAccountDriver { // instance vars and methods } Notes: The bankProgram package contains two files, BankAccount.java and BankAccountDriver.java. The BankAccountDriver class contains a method named main. Execution will begin with this method (more later).

Objects

Recall That an Object is … a particular instance of a class. For any of these accounts, one can … Deposit money Withdraw money Check the balance Transfer money Morawskis AccountRomanos AccountMitchells Account Susan Mitchell $ % Max Morawski $1, % Ross Romano $ % Version 9/1212

Creating and Using Objects Version 9/1213 Declaration and Initialization BankAccount myAccount; myAccount = new BankAccount( ); OR BankAccount myAccount = new BankAccount( ); Object Use: instance variables String myAcctNum = myAccount.accountNumber; float myBalance = myAccount.balance; Calling or host object Object Use: methods myAccount.deposit(50.25); double myBalance = myAccount.checkBalance( ); dot notation

Object Equality Objects are references. Cannot use == operator to test for equality Version 9/1214 public static void main(String[] args){ Car car1 = new Car(); Car car2 = new Car(); // code to customize both cars if(car1 == car2){ System.out.println("Same Car"); } else{ System.out.println("Different Cars"); } FF00 car1 FF20 car2 … … … …

Object Equality (cont) Solution: write an equals method for the class. Version 9/1215 public boolean equals(Car otherCar){ if(horsepower != otherCar.horsepower){ return false; } if(!make.equals(otherCar.make)){ return false; } //... compare necessary members... // otherwise, if all equal return true return true; } Notes: Returns a boolean Compares only Cars as implemented Definition of what constitutes equals may vary class to class

Version 9/1216 Printing an Object Given: Car car1 = new Car(parameters); executing System.out.println(car1); will result in something cryptic, such as Its usually a good idea to implement a method called toString in your class. public String toString() { String state = ""; state += "make: " + make; state += " model: " + model; //... return state; }

Program Documentation

Version 9/1218 Javadocs Java provides documentation for its API (the Java built-in class library). The documentation for each class contains class and method-level documentation. These documents are created using the Javadoc tool. Required for CMSC 202 project documentation Demonstrated in Lab 1

Version 9/1219 Example Javadoc for a Method /** * Changes the color of the calling object's color variable * color - a color that is real to change the car's color to the old color of the car */ public String changeColor(String color){ String old = this.color; this.color = color; return old; }

Required Class Documentation Version 9/1220 /** * This class models a traditional table * Class Invariants: * - A table must have either 3 or 4 legs * - A table must be round, rectangular, or oval 9/22/05 Bob Smith CMSC Spring Project 1 02 */ public class Table { /*...class definition... */ } Note: More on class invariants later.

Required Method Documentation Version 9/1221 /** * Calculates the area of a circle given its radius * Precondition: the radius must be >= zero * Postcondition: the area is calculated or zero returned if the radius is < zero radius: the radius of the circle the calculated area of the circle, or zero if an invalid * radius was supplied */ double circleCircleArea(double radius) { // handle unmet precondition if (radius < 0.0) { return 0.0; } else { return Math.PI * radius * radius; }

Version 9/1222 Pre-conditions & Post-conditions Pre-conditions – All assumptions made about parameters and the state of the calling object before a method is called – For example: The parameter mileage is non- negative. Post-conditions – All assumptions that can be made after method execution. – For example: The car will have a new paint color. Note: More on pre and post- conditions later.