1 Objects and Classes Introduction zNow that some low-level programming concepts have been established, we can examine objects in more detail zLecture.

Slides:



Advertisements
Similar presentations
Fields, Constructors, Methods
Advertisements

1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Lecture 6 b Last time: array declaration and instantiationarray declaration and instantiation array referencearray reference bounds checkingbounds checking.
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.
Chapter 4: Writing Classes
ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
Chapter 3, More on Classes & Methods Clark Savage Turner, J.D., Ph.D. Copyright 2003 CSTurner, from notes and text.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
Enhancing classes Visibility modifiers and encapsulation revisited
ECE122 L16: Class Relationships April 3, 2007 ECE 122 Engineering Problem Solving with Java Lecture 16 Class Relationships.
ECE122 L6: Problem Definition and Implementation February 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
1 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Classes, Encapsulation, Methods and Constructors
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Objects and Classes Objects and Classes objects defining classes method declaration object references and aliases instance variables encapsulation and.
COMP 14: Writing Classes June 6, 2000 Nick Vallidis.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java.
1 Lecture 4 Objects and Classes Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley John Lewis, Peter DePasquale, and Joseph Chase Chapter 5: Writing Classes.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
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.
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Software Solutions Lewis and Loftus Chapter 4 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects and Classes -- Introduction.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Chapter 4 Writing Classes Part 2. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Classes A class can contain data declarations and method declarations.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
© 2004 Pearson Addison-Wesley. All rights reserved September 12, 2007 Encapsulation ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
CSE 501N Fall ‘09 04: Introduction to Objects 08 September 2009 Nick Leidenfrost.
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Lecture 4 b Writing Classes b class declarations b method declarations b constructors b instance variables b encapsulation b method overloading b program.
Java Software Solutions Lewis and Loftus Chapter 3 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Program Elements -- Introduction.
Chapter 4: Writing Classes. 2 b We've been using predefined classes. Now we will learn to write our own classes to define new objects b Chapter 4 focuses.
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
1 Objects for Organizing Data -- Introduction zAs our programs get more sophisticated, we need assistance organizing large amounts of data zChapter 6 focuses.
1 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
1 Enhanced Class Design Introduction zWe now examine several features of class design and organization that can improve reusability and system elegance.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Copyright © 2014 Pearson Education, Inc.
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 5: Enhancing Classes
Chapter 4: Writing Classes
Chapter 7 User-Defined Methods.
Chapter 4: Writing Classes
Chapter 3: Using Methods, Classes, and Objects
Classes A class is a blueprint of an object
Chapter 4: Writing Classes
Encapsulation & Visibility Modifiers
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
Chapter 4: Writing classes
Classes, Encapsulation, Methods and Constructors (Continued)
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Packages & Random and Math Classes
Encapsulation September 13, 2006 ComS 207: Programming I (in Java)
Presentation transcript:

1 Objects and Classes Introduction zNow that some low-level programming concepts have been established, we can examine objects in more detail zLecture focuses on: ythe concept of objects ythe use of classes to create objects yusing predefined classes ydefining methods and passing parameters ydefining classes yvisibility modifiers ystatic variables and methods ymethod overloading

2 Objects zAn object has: ystate - descriptive characteristics ybehaviors - what it can do (or be done to it) zFor example, a particular bank account yhas an account number yhas a current balance ycan be deposited into ycan be withdrawn from

3 Classes zA class is a blueprint of an object zIt is the model or pattern from which objects are created zA class defines the methods and types of data associated with an object zCreating an object from a class is called instantiation; an object is an instance of a particular class  For example, the Account class could describe many bank accounts, but toms_savings is a particular bank account with a particular balance

4 Creating Objects  The new operator creates an object from a class: Account toms_savings = new Account();  This declaration asserts that toms_savings is a variable that refers to an object created from the Account class  It is initialized to the object created by the new operator zThe newly created object is set up by a call to a constructor of the class

5 Constructors zA constructor is a special method used to set up an object zIt has the same name as the class zIt can take parameters, which are often used to initialize some variables in the object  For example, the Account constructor could be set up to take a parameter specifying its initial balance: Account toms_savings = new Account(125.89);

6 Object References zThe declaration of the object reference variable and the creation of the object can be separate activities: Account toms_savings; toms_savings = new Account(125.89); zOnce an object exists, its methods can be invoked using the dot operator: toms_savings.deposit(35.00);

7 The String Class  A character string in Java is an object, defined by the String class String name = new String("Ken Arnold"); zBecause strings are so common, Java allows an abbreviated syntax: String name = "Ken Arnold"; zJava strings are immutable; once a string object has a value, it cannot be changed

8 The String Class zA character in a string can be referred to by its position, or index zThe index of the first character is zero  The String class is defined in the java.lang package (and is therefore automatically imported)  Many helpful methods are defined in the String class  See Carpe_Diem.javaCarpe_Diem.java

9 The StringTokenizer Class  The StringTokenizer class makes it easy to break up a string into pieces called tokens zBy default, the delimiters for the tokens are the space, tab, carriage return, and newline characters (white space)  The StringTokenizer class is defined in the java.util package  See Int_Reader.javaInt_Reader.java

10 The Random Class zA program may need to produce a random number  The Random class provides methods to simulate a random number generator  The nextInt method returns a random number from the entire spectrum of int values zUsually, the number must be scaled and shifted into a particular range to be useful  See Flip.javaFlip.java

11 The Random Class Expression Math.abs (rand.newInt()) % Math.abs (rand.newInt()) % Math.abs (rand.newInt()) % 101 Math.abs (rand.newInt()) % Math.abs (rand.newInt()) % Range 1 to 6 1 to 10 0 to to to 5

12 References zAn object reference holds the memory address of an object Chess_Piece bishop1 = new Chess_Piece(); zAll interaction with an object occurs through a reference variable zReferences have an effect on actions such as assignment bishop1

13 Assignment zThe act of assignment takes a copy of a value and stores it in a variable zFor primitive types: num2 = num1; Before num1 5 num2 12 After num1 5 num2 5

14 Reference Assignment zFor object references, the value of the memory location is copied: bishop2 = bishop1; Before bishop1bishop2 After bishop1bishop2

15 Aliases zTwo or more references that refer to the same object are called aliases of each other zThere is only one copy of the object (and its data), but with multiple ways to access it zAliases can be useful, but should be managed carefully zAffecting the object through one reference affects it for all aliases, because they refer to the same object

16 Garbage Collection zWhen an object no longer has any valid references to it, it can no longer be accessed by the program zIt is useless, and therefore called garbage zJava performs automatic garbage collection periodically, returning an object's memory to the system for future use zIn other languages, the programmer has the responsibility for performing garbage collection

17 Methods zA class contains methods; prior to defining our own classes, we must explore method definitions  We've defined the main method many times zAll methods follow the same syntax: return-type method-name ( parameter- list ) { statement-list }

18 Methods zA method definition: int third_power (int number) { int cube; cube = number * number * number; return cube; } // method third_power

19 Methods zA method may contain local declarations as well as executable statements zVariables declared locally can only be used locally  The third_power method could be written without any local variables: int third_power (int number) { return number * number * number; } // method third_power

20 The return Statement zThe return type of a method indicates the type of value that the method sends back to the calling location  A method that does not return a value (such as main ) has a void return type zThe return statement specifies the value that will be returned zIts expression must conform to the return type

21 Method Flow of Control  The main method is invoked by the system when you submit the bytecode to the interpreter zEach method call returns to the place that called it mainmethod1 method2 method1(); method2();

22 Parameters zA method can be defined to accept zero or more parameters zEach parameter in the parameter list is specified by its type and name zThe parameters in the method definition are called formal parameters zThe values passed to a method when it is invoked are called actual parameters

23 Parameters zWhen a parameter is passed, a copy of the value is made and assigned to the formal parameter zBoth primitive types and object references can be passed as parameters zWhen an object reference is passed, the formal parameter becomes an alias of the actual parameter  See Parameter_Passing.javaParameter_Passing.java  Usually, we will avoid putting multiple methods in the class that contains the main method

24 Defining Classes zThe syntax for defining a class is: class class-name { declarations constructors methods } zThe variables, constructors, and methods of a class are generically called members of the class

25 Defining Classes class Account { int account_number; double balance; Account (int account, double initial) { account_number = account; balance = initial; } // constructor Account void deposit (double amount) { balance = balance + amount; } // method deposit } // class Account

26 Constructors zA constructor: yis a special method that is used to set up a newly created object yoften sets the initial values of variables yhas the same name as the class ydoes not return a value  has no return type, not even void zThe programmer does not have to define a constructor for a class

27 Classes and Objects zA class defines the data types for an object, but a class does not store data values zEach object has its own unique data space zThe variables defined in a class are called instance variables because each instance of the class has its own zAll methods in a class have access to all instance variables of the class zMethods are shared among all objects of a class

28 Classes and Objects Class Objects int account_number double balance account_number balance account_number balance

29 Encapsulation zYou can take one of two views of an object: yinternal - the structure of its data, the algorithms used by its methods yexternal - the interaction of the object with other objects in the program zFrom the external view, an object is an encapsulated entity, providing a set of specific services zThese services define the interface to the object

30 Encapsulation zAn object should be self-governing; any changes to the object's state (its variables) should be accomplished by that object's methods zWe should make it difficult, if not impossible, for another object to "reach in" and alter an object's state zThe user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished

31 Encapsulation zAn encapsulated object can be thought of as a black box; its inner workings are hidden to the client client toms_savings deposit withdraw add_interest produce_statement

32 Abstraction zEncapsulation is a powerful abstraction zAn abstraction hides the right details at the right time zWe use abstractions every day: ydriving a car yusing a computer zEncapsulation makes an object easy to manage mentally because its interaction with clients is limited to a set of well-defined services

33 Visibility Modifiers zWe accomplish encapsulation through the appropriate use of visibility modifiers zA modifier is a Java reserved word that specifies particular characteristics of a programming construct  We've used the modifier final to define a constant  Java has three visibility modifiers: public, private, and protected  We will discuss the protected modifier later

34 Visibility Modifiers zMembers of a class that are declared with public visibility can be accessed from anywhere zMembers of a class that are declared with private visibility can only be accessed from inside the class zMembers declared without a visibility modifier have default visibility and can be accessed by any class in the same package zJava modifiers are discussed in detail in Appendix F

35 Visibility Modifiers zAs a general rule, no object's data should be declared with public visibility zMethods that provide the object's services are usually declared with public visibility so that they can be invoked by clients zPublic methods are also called service methods zOther methods, called support methods, can be defined that assist the service methods; they should not be declared with public visibility

36 Classes and Objects  See tunes.javatunes.java main music add_cds print

37 The static Modifier  The static modifier can be applied to variables or methods zIt associates a variable or method with the class rather than an object zThis approach is a distinct departure from the normal way of thinking about objects

38 Static Variables zNormally, each object has its own data space zIf a variable is declared as static, only one copy of the variable exists for all objects of the class private static int count; zChanging the value of a static variable in one object changes it for all others zStatic variables are sometimes called class variables

39 Static Methods zNormally, we invoke a method through an instance (an object) of a class zIf a method is declared as static, it can be invoked through the class name; no object needs to exist  For example, the Math class in the java.lang package contains several static mathematical operations Math.abs (num) -- absolute value Math.sqrt (num) -- square root

40 Static Methods  The main method is static; it is invoked by the system without creating an object zStatic methods cannot reference instance variables, because instance variables don't exist until an object exists zHowever, they can reference static variables or local variables zStatic methods are sometimes called class methods

41 Overloaded Methods zMethod overloading is the process of using the same method name for multiple methods zThe signature of each overloaded method must be unique zThe signature is based on the number, type, and order of the parameters zThe compiler must be able to determine which version of the method is being invoked by analyzing the parameters zThe return type of the method is not part of the signature

42 Overloaded Methods  The println method is overloaded: println (String s) println (int i) println (double d) etc. zThe lines System.out.println ("The total is:"); System.out.println (total); invoke different versions of the println method

43 Overloaded Methods zConstructors are often overloaded to provide multiple ways to set up a new object Account (int account) { account_number = account; balance = 0.0; } // constructor Account Account (int account, double initial) { account_number = account; balance = initial; } // constructor Account  See Casino.javaCasino.java

44 Classes and Objects  See purchase_power.java purchase_power.java jim bob beans franks name "Bob" Manager Purchase_Power name "Jim" Manager name "beans" Stock_Item product_buyer name "franks" Stock_Item product_buyer

45 Classes and Objects  See Storm.javaStorm.java drop1 drop2 drop3 drop4 drop5 Storm current_size 18 current_size 4 12 current_size 7 24