Post on 24-Dec-2015
What is an Object?You can look around you now and see many examples of real-world objects: a desk, computer, chair, person, etc.
An object has a (current) state and behavior. A dog has state (name, color, breed, hungry) and behavior (barking, fetching, and wagging tail). Another simple example:
A Light
State: On/Off
Behavior: We can switch light on or off.
An Object in Software
A real world object may be represented in software.
Different variables represent the state of the object.
Various methods/functions represent the behavior of the object.
Object Type: Light
Variable: boolean switchState;
Function: void turnSwitch(boolean on) { …. }
Each object has a type/class.
An object is an instance of a class/type. We write new classes to define new types of objects.
A particular object resembles other objects of its type. A few variables of an object may be shared by all objects of the same type.
An Object can be mutable (has changing state) or immutable (its methods do not change its state).
Objects can inherit properties, both state and behavior, from other objects.
Properties of Objects
An Apple is a type of object.
A particular apple, perhaps a Green Apple is an instance of the Apple class/type.
A particular object resembles other objects of its type. A Green Apple object resembles another Red Apple object through its type (both are apples). However, varying colors.
An Object can be mutable or immutable. If immutable, a Red apple cannot change state. If mutable, we are allowed to paint the apple another color and change its color property.
Objects of type Apple may inherit properties from objects of type Fruit. Apple is-a Fruit.
Object Example
Object Oriented Design We view everything as an object. We can build
layers of abstraction by writing new types of objects that are defined in terms of previous object types. A Line class may be defined in terms of a Point class.
A program is a collection of objects interacting through messages (ie. methods). Other ways of thinking about message passing: Sending events (event objects).
Ex: A Mouse Click on your computer screen sends
an event to the Panel object.
Object Oriented Programming
High Level Abstraction: Design simplicity amidst complex tasks. A programmer represents a problem using the terms of the problem.
Example: We don’t worry about how a String object is implemented, but we know that we can add two strings somehow We view a String object as an abstraction. We use functions of Strings, but don’t worry about how each function was written.
Examples of Abstraction
- File Object: Hides complexity of reading, writing, searching, copying, moving a data file.
- Socket object: Hides complexity of a connection between client and server machines.
- Graph object: Hides complexity of a system of node objects and link objects, representing a possible network or map system.
Types Of Objects
Primitive Types: boolean, char, int, double, void, (byte, short, long, float).
Complex TypesMust create objects of complex types, usually with the new
keyword to call the object constructor. Java Defined Types: String error_msg = new String(“Err1”); Character yes = new Character(‘y’); [Java: Some cases, no new. String error_msg = “Err1”;] User Defined Types: Classes written by programmer.
Create object using constructor, always use new.
A Familiar Java Defined Type
java.lang.String
Construct object: String str = “abcd”; String str = new String(“abcd”);
State: Immutable. State is a string of characters.
Behavior: Can use following example functions with a String-
charAt(int index) : Will return character at specified index.concat(String s) : Will return new string that adds s to itself.length() : Will return integer length of this string.toUpperCase() : Will return a new string with upper case
characters.
A New Type Called Apple
Construct object: Apple greenApple = new Apple(“green”); Apple redApple = new Apple(“red”);
State: State is color (red/green/yellow). Should be immutable.
Behavior: Can slice an apple. Can look at its color.
String getAppleColor() : Returns the string form of the apples color
void sliceApple() : Performs task of slicing the apple and returns void.
Outline of a Class Definition
There is no public static void main() method defined in class Apple.
class Apple { // Data Fields to record state of Apple.
// Constructor for Making a New Apple.
// Methods for Behavior of Apple.
}
Apple Class – Writing the code.
class Apple {
// Data Fields to record state of Apple. String color;
// Constructor for Making a New Apple. Apple(String c) { color = c; }
// Methods for Behavior of Apple. String getAppleColor() { return color; } void sliceApple() { System.out.println(“You sliced this ” + color + “
apple.”); }}
Constructors
Class Apple has a constructor:
Apple(String c) { color = c;}
A constructor is a special method that has no return type. The constructor name is EXACTLY the same as the class
name: Apple A constructor constructs a new object using the new
keyword: Apple redApple = new Apple(“red”);
A constructor must initialize the state of the Apple object. In this case, the constructor expects a color, then initializes its own color to the given color specified.
A New Object vs. Object References
Class Apple example:A REFERENCE Points to An Object:
Apple redAppleOne = new Apple(“red”);Apple redAppleRef = redAppleOne;
Apple yellowApple = new Apple(“yellow”);
What happens after this:yellowApple = redAppleOne;
“red”getAppleColor()sliceApple()
redAppleOne
redAppleRef
“yellow”getAppleColor()sliceApple()yellowApple
Objects and References Example
Class Apple example:
1. Create a red apple, and a yellow apple.2. Call the reference to the red apple
redApple (picture )3. Call the reference to the yellow apple
yellowApple (picture )
4. GOAL: Switch references so that reference redApple points to the object that is a yellow apple. And, switch so that yellowApple reference points to the object that is actually a red apple.
“red”getAppleColor()sliceApple()
redApple
“yellow”getAppleColor()sliceApple()yellowApple
Using the Apple Class
We can use the Apple class now as follows: We write another class (here, called Application) that
includes the main() method.
class Application {
public static void main(String[] args) {
System.out.println(“Hello World Again !”); Apple greenApple = new Apple(“green”); System.out.println(“I made a ” + greenApple.getAppleColor()
+ “ apple, and I am learning objects.”);
}
Using Apple Methods
We can write more statements (using Apple methods) in another class (for example, the Application class)
What would these statements print out?
Apple redApple = new Apple(“red”);System.out.println(“We made a ” + redApple.getAppleColor() + “
apple.”);
redApple.sliceApple();
redApple.color = “green”;System.out.println(“We made a ” + redApple.getAppleColor() + “
apple.”);
LAST TWO LINES INTRODUCE ISSUE OF ACCESS INTO OBJECT.
redApple.color = “green”;System.out.println(“We made a ” + redApple.getAppleColor() + “ apple?”);
We created a new red apple.However, we can access the red apple’s color outside the class, and somehow change it to green. This is obviously not what we want.
Want to limit access:In the Apple class, we should have written:
private String color; // Now, can’t change color outside Apple class.
Access Into Objects
Private, Public, Nothing Specified.
Private: Can only access variable or method within the class itself. (Within Apple class)
Public: Can access variable or method everywhere. (Inside Apple class and Application class)
Nothing Specified: So far, we have not specified any private or public access. This means
the variable or method is accessible in the same package (for now, this means same as public)
Completed Apple Class
public class Apple {
// Data Fields to record state of Apple. private String color;
// Constructor for Making a New Apple. public Apple(String c) { color = c; }
// Methods for Behavior of Apple. public String getAppleColor() { return color; } public void sliceApple() { System.out.println(“You sliced this “ + color + “
apple.”); }}
Summary
redApple.color can’t write this statement anymore. The access to the object’s color field in the Application class is prohibited.
Once we create an apple with a certain color, then it can’t change.
IF we were writing a leaf class, we might want to have its color be changeable as the seasons change.
Next Lecture: More Interesting Objects
Sample Exercise 1
Write a Simple Student class.
What information do we want to
represent a Student?
Name, email address, etc.
Any methods/functions needed?
Sample Exercise 2
Write a simple class called PhoneBook
A PhoneBook constructor takes an array of names and an array of phone numbers (corresponding to the names).
Methods of a PhoneBook could be:
int findPhoneNumber(String personName) { ….. }
boolean isInPhoneBook(String personName) { …. }
String lookUpPerson(int phoneNumber) { …… }
int sizeOfPhoneBook() { ….. }