CSE 501N Fall ‘09 04: Introduction to Objects 08 September 2009 Nick Leidenfrost.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
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.
1 Objects, Classes, and Packages “Static” Classes Introduction to Classes Object Variables and Object References Instantiating Objects Using Methods in.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Chapter 3 – Implementing Classes. Chapter Goals To become familiar with the process of implementing classes To be able to implement simple methods To.
ECE122 L4: Creating Objects February 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects.
Road Map Introduction to object oriented programming. Classes
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
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.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
ECE122 L6: Problem Definition and Implementation February 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
References, Aliases, Garbage Collection and Packages Packages and Importing Classes Reading for this Lecture: L&L, Familiarize yourself with.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
1 Lecture 4 Objects and Classes Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
BPJ444: Business Programming Using Java Classes and Objects Tim McKenna
Introduction to Object-Oriented Programming
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.
Classes CS 21a: Introduction to Computing I First Semester,
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
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.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
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.
Introduction to Java Java Translation Program Structure
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 5 Introduction to Defining Classes
SEEM Java – Basic Introduction, Classes and Objects.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
1 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
© 2004 Pearson Addison-Wesley. All rights reserved January 23, 2006 Creating Objects & String Class ComS 207: Programming I (in Java) Iowa State University,
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
© 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.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Topic: Classes and Objects
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
Creating Objects & String Class
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
Creating Objects A variable holds either a primitive value or a reference to an object A class name can be used as a type to declare an object reference.
Packages & Random and Math Classes
JAVA CLASSES.
Java Programming Language
Outline Creating Objects The String Class The Random and Math Classes
Presentation transcript:

CSE 501N Fall ‘09 04: Introduction to Objects 08 September 2009 Nick Leidenfrost

2 Lecture Outline Lab 1 Static Methods Objects  Fields / Instance Variables  Object Variables Aliases  Creating Objects: Constructors  Accessing Fields / Invoking methods on Objects The String Object Object Assignment Access Modifiers Variable Scopes

3 Static Methods Calling Methods Without Objects In Java, all methods must be defined within a class body At times it is useful to have a method which defines functionality that does not alter the state of an object  The Java Library class java.lang.Math is a perfect example of useful static methods Methods in Math give us functionality that is not native to the Java language These functions are strictly input / output functions and do not alter the state of any Math object

4 Static Methods Calling / Invoking Static methods are typically invoked in the following way: int myNum = 5; int cubed = Math.pow(myNum, 3);.

5 Classes Further detail A class is a template (or blueprint) for creating Objects  Often representative of real-world concepts  Defines state (fields)  Defines behavior (methods) public class BankAccount { // Fields / Methods defined here. }

6 Class Members: Fields Thinking in OO An class’s fields (a.k.a. instance variables) define the internal state Just as classes often mimic real-world concepts, fields often represent real attributes of those concepts public class BankAccount { double balance; int accountNumber; Person owner; }

7 Class Members: Fields Referencing Fields Fields can be used in all class methods by name public class BankAccount { double balance; int accountNumber; } public double getBalance () { return balance; } There is no local variable declared in this method named balance. Therefore, Java knows we are referring to the instance variable.

8 Objects Objects are instances of classes  (Real examples of the concept defined by a class) Each object gets its own copy of all instance variables  This internal state is specific to each object George’s BankAccount balance accountNum 14, Nick’s BankAccount balance accountNum Sally’s BankAccount balance accountNum 1,584,

9 Object Variables Declaring Variables with Object Types We can declare variables to hold Object values just like we can with primitives A class name is used as the type when declaring an object variable Note that no object is created with this declaration  Object variables hold the special value null if they are not initialized The object itself must be created separately  With its constructor String title;

10 Aliases Two or more references (variables) that refer to the same object are called aliases of each other That creates an interesting situation: one object can be accessed using multiple reference variables Aliases will naturally occur in programming, but should be managed carefully  Changing an object through one reference changes it for all of its aliases, because there is really only one object

11 Creating Objects Constructors Constructors are special methods that create the objects of a class  Allocate Memory required to store object state (instance variables);  Initialize object state per programmer instructions Constructors give the programmer a chance to initialize the state (instance variables) of an object Constructors must have the same name as the class in which they are defined Constructors have no return type specified in the method header, not even void public class BankAccount { public BankAccount () { // Initialization code here }

12 Creating Objects Constructors Can accept parameters like methods Each class has a default constructor that accepts no parameters  The programmer does not have to define a constructor for a class - Java will define a default constructor for us if we do nothing public BankAccount (int accountNum, double amount) { … } protected BankAccount () { } Can also be overloaded like methods

13 Creating Objects The new Operator Generally, we use the new operator to invoke an object’s constructor BankAccount account = new BankAccount(156774, 0.0); The new operator is used to invoke the constructor The constructor cannot be called without new Creating an object is called instantiation

14 Creating Objects Overloaded Constructors If a constructor is overloaded we can call one version from another with the this keyword this also has other uses that we will learn about soon. public BankAccount (int accountNumber, double initBalance) { accountNum = accountNumber; balance = initBalance; } public BankAccount (int accountNumber) { this(accountNumber, 0.0); }

15 Creating Objects Return Statements Constructors by definition return an object whose type is that of the constructors’ class You may have a return statement inside of a constructor  Only for returning from the constructor call early  You may not return a value

16 Invoking Methods on Objects Once an object has been instantiated, we can use the dot operator to invoke its methods  Dot operator syntax: A method invocation can be thought of as asking an object to perform a service or to manipulate its state BankAccount acct = new BankAccount(); double balance = acct.getBalance();.

17 double getBalance() void helper () helper(); acct.getBalance(); void main () Method Control Flow The called method may be part of another class or object ATM BankAccount

18 Referencing Fields of Objects Once an object has been instantiated, we can also use the dot operator to access its fields Referencing fields in this way is generally discouraged with a few exceptions Instance variables should typically be accessed and modified using accessor and mutator methods BankAccount account = new BankAccount(); // … omitted statements double canSpend = account.balance; account.balance = 15000;

19 The String Object A Primitive? An Object? Superman? Earlier, we learned about the char data type, used to store a single character In Java, the String object represents a series (or string) of characters String constants in Java are encapsulated by double quotes  String name = “Peter”; Strings are Objects in Java  Lots of predefined functionality  int length = name.length(); Also referred to as string literals

20 The String Class Because strings are so common, we don't have to use the new operator to create a String object with a string constant / string literal String text = “was it a rat I saw"; This is special syntax that works only for strings Each string literal (enclosed in double quotes) represents a String object Java implicitly calls the String constructor when a String literal is assigned to String variables

21 The String Object Strings can be “added” like numeric primitives with the ‘+’ and ‘+=‘ operators  This is referred to as concatenation String firstName = “George”; String lastName = “Henrichs”; String name = firstName + “ “ + lastName; // “George Henrichs” //...Or String name = lastName; name += “, “ + firstName;// “Henrichs, George”

22 The String Object Strings can be also concatenated with primitive types: The resultant type of an expression is the widest type of the operands of that expression  Strings are “wider” than any type String name = “George”; double examGrade = 89.7; String output = name + “ received an “ + examGrade + “% on exam 1”; // “George received an 89.7% on exam 1”

23 Of Strings and Objects The toString Method We can define a special method toString to specify the String representation of an object  A default implementation of toString is provided for us if we don’t define one This allows object variables to be concatenated with Strings: BankAccount account = new BankAccount(10000, ); System.out.println(“The account: “ + account); public String toString () { return accountNum + “: “ + balance; }

24 Printing Strings to the Command Line System.out.print and System.out.println We can print any String to the command line with two methods provided by Java  System.out.print  System.out.println String name = “George”; double examGrade = 89.7; String output = name + “ received an “ + examGrade + “% on exam 1”; System.out.println(output);

25 String Methods Immutable Objects Once a String object has been created, neither its value nor its length can be changed Thus we say that an object of the String class is immutable However, several methods of the String class return new String objects that are modified versions of the original

26 Variable Declaration Primitive Variables vs. Object Variables Your Computer’s Memory (RAM) int myCount; String name; When a variable is declared, whether it’s a primitive or an object, Java allocates memory to store the variable 0 4 bytes null 4 bytes Really, a variable is just a human-readable “nickname” for a memory address If the variable is a primitive, the appropriate amount is allocated based on the variable’s type e.g. 8 bytes for a double 4 bytes for an int 1 byte for a char …etc. If the variable is an object, 4 bytes are allocated for the object handle. This memory will later point to the object referenced by ‘name’. Any value the primitive variable will ever have will be stored in this memory.

27 Variables and Assignment Primitive Variables vs. Object Variables Assignment Affects Object and Primitive Variables Differently Your Computer’s Memory (RAM) 0 4 bytes int myCount; String name; myCount = 2; name = new String(“Bob”); null 4 bytes “Bob” store 2 (Memory Address) When the constructor is invoked (called) Java allocates memory for the object. The object handle now refers to the newly created object.

28 Object Variable Reassignment Your Computer’s Memory (RAM) String name; name = new String(“Bob”); name = “Robert”; (Memory Address) “Bob” “Robert” Implicitly calls the String constructor

29 Object Aliases Two References to the Same Object (Multiple References to the Same Object) String name = “Bob”; String aName; aName = name; name = null; String anotherName = “Bob”; Your Computer’s Memory (RAM) (Memory Address) “Bob” null (Memory Address) null “Bob” (Memory Address) null

30 Primitive Assignment Value is copied int myCount = 2; int numGuests; numGuests = myCount; Your Computer’s Memory (RAM) 2 0 2

31 Object Interaction Access Modifiers Access modifiers allow us to control who has access to an object’s members  Who can reference Fields (internal state)  Who can invoke Methods (behavior)  Who can invoke Constructors Java provides four types of access modifiers  public Anyone can read and write this field or invoke this method  protected Only other instances of this class and their subclasses  [default] or Package Protected (No access modifier specified) Only other classes in the package  private Only this object and other instances of this class

32 Object Interaction Access Modifiers Using Modifiers to Protect State public class BankAccount { private double balance; protected BankAccount () { } public boolean deposit (double amount) { if (amount <= 0) return false; balance += amount; return true; } public boolean withdraw (double amount) { if (amount <= 0) return false; double newBalance = balance – amount; balance = newBalance; return true; } … in instance variable declarations … in method declarations Note that local variables (variables declared within methods) cannot have access modifiers. protected and private default constructors can be created to prevent Java from defining a public default constructor

33 Object Interaction Encapsulation We may not want to give others unlimited access to an object’s state Force the outside world to interact with a class and its state through predefined methods BankAccount account = new BankAccount(); //... double balance = account.balance; double balance = account.getBalance(); Generally, it is a bad idea to allow direct access to a class’s fields. Accessor methods allow access to required information without exposing objects fields

34 Object Interaction Encapsulation If an access modifier is used when a class member is declared, any access prohibited by that access modifier becomes a compilation error public class BankAccount { private double balance; // Omitted methods, etc } // Outside of BankAccount.java BankAccount account = new BankAccount(); //... double balance = account.balance; The field BankAccount.balance is not visible. X

35 Scopes The Lifespan and Visibility of a Variable A scope of a variable defines the context in which it is accessible Usually surrounded by brackets: { } S tate or instance variables are accessible from any method in the class  If declared public / default / protected, accessible from other classes as well Local variables are accessible only within the method in which they are declared  Local variables “die” after the method returns

36 Local Variables As we’ve seen, local variables can be declared inside a method The formal parameters of a method create automatic local variables when the method is invoked  Primitive parameters are copied  Object parameters are aliased What happens in the method doesn’t necessarily stay in the method When the method finishes, all local variables are destroyed (including the formal parameters) Keep in mind that instance variables, declared at the class level, exists as long as the object exists

37 Garbage Collection Automatic Memory Management When an object no longer has any valid references to it, it can no longer be accessed by the program The object is useless, and therefore is called garbage Java performs automatic garbage collection periodically, returning an object's memory to the system for future use In other languages, the programmer is responsible for performing garbage collection

38 Conclusion Questions? Lab 1 due Thursday I will be in lab now.