Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CSE 501N Fall ‘09 04: Introduction to Objects 08 September 2009 Nick Leidenfrost."— Presentation transcript:

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

2 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 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 4 Static Methods Calling / Invoking Static methods are typically invoked in the following way: int myNum = 5; int cubed = Math.pow(myNum, 3);.

5 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 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 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 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,068.00 3988323425 Nick’s BankAccount balance accountNum -573.17 1858323356 Sally’s BankAccount balance accountNum 1,584,001.01 225323693

9 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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, 50000.0); System.out.println(“The account: “ + account); public String toString () { return accountNum + “: “ + balance; }

24 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 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 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 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 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 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 30 Primitive Assignment Value is copied int myCount = 2; int numGuests; numGuests = myCount; Your Computer’s Memory (RAM) 2 0 2

31 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 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 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 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 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 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 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 38 Conclusion Questions? Lab 1 due Thursday I will be in lab now.


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

Similar presentations


Ads by Google