Upload
tareq-hasan
View
8.832
Download
1
Tags:
Embed Size (px)
DESCRIPTION
Sub: Java Topic: Objects and Object References Slide number: 8 Presented by: Mahbubul Islam (MMI) Lecturer, Dept. of CSE University of Rajshahi
Citation preview
1
Objects and Object References
2
What is an Object?
Think about the things in the world that are objects?» A pen is an object.
» A computer keyboard is an object.
» Bank account is an object
» The class room is an object
So, what all objects have in common?» An object has identity (it acts as a single whole).
» An object has state (it has various properties, which might change).
» An object has behavior (it can do things and can have things done to it).
» Example:– you can think of your bank account as an object. Your account has properties (the
balance, interest rate, owner) and you can do things to it (deposit money, cancel it) and it can do things (charge for transactions, appreciate interest.)
3
Software objects
It is convenient to have "software objects" that are similar to "real world objects." This makes the program and its computation easier to think about.
Software objects will have identity, state, and behavior just as do real world objects. Of course software objects exist entirely within a computer system and don't directly affect real world objects.» Software objects have identity because each is
a separate chunk of memory. » Software objects have state. Some of the
memory that makes a software object is used for variables which contain values.
» Software objects have behavior. Some of the memory that makes a software object is used to contain programs (called methods) that enable the object to "do things." The object does something when one of its method runs.
Both variables and methods are called “members” of the object.
Variablesbalanceinterest rateowner
Methodsdeposit()withdraw()charge()
Bank account
Ch
un
k of
mem
ory
4
Using a Class to make Objects
A class is like a cookie cutter that can be used many times to make many cookies. There is only one cookie cutter, but can be used to make many cookies.
Different cookies may have different characteristics, even though they follow the same basic pattern.
Cookies can be created. And cookies can be destroyed (just ask Cookie Monster). But destroying cookies does not affect the cookie cutter.
To create an object, there needs to be a description of it. A Class is a description of a kind of object.
5
When a programmer wants to create an object the new operator is used with the name of the class. Creating an object is called instantiation.
Once the object has been created (with the new operator). The variable str1 is used to refer to this object.
Java uses "dot notation" to access any of its members as follows:
referenceToAnObject.memberOfObject Method names have "()" at their end. Often there is additional information
inside the "()", but they are required even if they contain nothing.
class StringTester { public static void main ( String[] args ) {
String str1; // str1 is a variable that refers to an object, // but the object does not exist yet.
int len; // len is a primitive variable of type int
str1 = new String("Salam Shabaab");//create an object of type String
len = str1.length(); // invoke the object's method length()
System.out.println("The string is " + len + " characters long"); } }
Example Program
6
Constructors
A constructor has the same name as the class. The line from the above program
str1 = new String("Salam Shabaab");
creates a new object of type String. The new operator says to create a new object. It is followed by the name of a constructor. The constructor String() is part of the definition for the class String.
Constructors often are used with values (called parameters) that are to be stored in the data part of the object that is created. In the above program, the characters "Salam Shabaab" (not including the quote marks) are stored in the new object.
There are usually several different constructors in a class, each with different parameters. Sometimes one is more convenient to use than another, depending on how the new object's data is to be initialized.
7
Primitive data types & Objects In Java, a piece of data either is of a primitive data type or is an object data type.
The only type of data a programmer can define is an object data type (a class). Every object in Java is an instance of a class. The class definition has to exist first before an object can be constructed.
A programmer may define a class using Java, or may use predefined classes that come in class libraries (like String).
Primitive Data
Objects
intlongfloat
doublechar
boolean
String
Applet
Graphics
8
Object References An object reference is information on how to find a particular object. The object is a
chunk of main memory; a reference to the object is a way to get to that chunk of memory.
Objects are created while a program is running. Each object has a unique object reference, which is used to find it. When an object reference is assigned to a variable, then that variable says how to find that object.
In Java, there are only primitive variables and object reference variables, and each contains a specific kind of information:
Kind of Variable Information it Contains When on the left of "="
primitive variable Contains actual data. Previous data is replaced with
new data.
reference variable Contains information on how to find an object.
Old reference is replaced with a new reference
9
Object References - Examples
Example of two objects and two reference variables:
Example of one object and two reference variables
String strA = new String (“Java”);String strB = new String (“C++”);
JAVAJAVAstrA
C++C++strB
String strA = new String (“Java”);String strB = strA
JAVAJAVAstrA
strB
10
Equality of Reference Variable Contents
The == operator does NOT look at objects! It only looks at references (information about where an object is located.)
strA == strB is true strA == strB is false
srtA.equals(strB) is true strA.equals(strB) is true
11
Using Objects and Classes
12
The Class Point
A 2D geometrical point has two values that describe the location of the point in xy-plane.
So, it’s better to think of a point as a single "thing" (not as two separate things.)
Java comes with a library of predefined classes that are used for building graphical user interfaces. This library is called the Application Windowing Toolkit, or the AWT. One of the many classes defined in this library is the class Point.
13
The Class Point Description
public class java.awt.Point
// Fieldsint x; int y;
// ConstructorsPoint(); // creates a point at (0,0)Point(int x, int y); // creates a point at (x,y)Point( Point pt ); // creates a point at the location given in pt
// Methodsboolean equals(Object obj); // checks if two point objects hold equivalent datavoid move(int x, int y); // changes the (x,y) data of a point object String toString(); // returns character data that can be printed
(I've left out some methods we won't be using.)
14
Using the Class Point
To create an object point, we may write the following code:Point a;
a = new Point();
The previous code can be rewritten as follow:Point a = new Point();
Can you create a point at location (12, 7) ?
Can you write a code to use the last constructor?
a
a 0, 0
move()equals()
toString()
0, 0
move()equals()
toString()
// ConstructorsPoint(); Point(int x, int y); Point( Point pt );
15
toString() method
The method toString() can be used to create a printable String for a given object.
public String toString();
The toString() method does not require any parameters. (it’s called parameter-less method.)
Point a = new Point(12, 7);
String str;
str = a.toString();
System.out.println(str);
The previous example can be modified as follow:Point a = new Point(12, 7);
System.out.println(a.toString());
When toString() is provided in class definition, it is automatically invoked when object name is used where String object is expected.
– Example: System.out.println( a );
This is a request to run a method of an object. The object referenced by a contains a method toString() which, when called, returns the contents as a String. The reference variable str is used to refer to String Object.
This is a request to run a method of an object. The object referenced by a contains a method toString() which, when called, returns the contents as a String. The reference variable str is used to refer to String Object.
16
Equivalent Data and Alias Example 1:
Point pt1 = new Point(5, 9);Point pt2 = new Point(5, 9);
» The variable pt1 and the variable pt2 are referring to different objects, but both objects have equivalent data.
Example 2:Point pt3 = new Point(5, 9);Point pt4 = pt3;
» The variable pt3 and the variable pt4 are referring to the same object. So, each reference variables is said to be an alias.
equals() method is used to test if the two objects contain equivalent data.
– Example: if ( pt1.equals(pt2) ) ...
== operator is used to test if the two reference variables refer to the same object.
– Example: if ( pt3 == pt4 ) ...
17
move() Method Is used to change the x and the y values inside a Point object. The description of the method move() inside class Point:
public void move( int x, int y );» The modifier public means that it can be used anywhere in your program» void means that it does not return a value. » ( int x, int y ) says that when you use move, you need to supply two int
parameters that give the new location of the point. Example:
Point a = new Point(12, 7);System.out.println( a );a.move(10, 13);System.out.prinltn( a );
You can put expressions into parameter lists as long as the expression evaluates to the type expected by the method.» Example:
a.move(20-12, 30*3-45); // equivalent to a.move(8,45)
java.awt.Point[x=12,y=7]java.awt.Point[x=10,y=13]
18
Type casting
A cast is an explicit conversion of a value from its current type to another type.
The syntax for a cast is: (requiredType) (expression)
» Example:Point pt = new Point();
short a = 13;
a.move(a, (int)14.6359 );
int
long
float
double
loss of information
Casting is required when converting to a required type will result in loss of information.
However, when a conversion from one type to another type can be done without loss of information, the compiler will do it automatically
19
Static Methods
In Java language, a characteristic of a class definition that is not shared by its objects is called static. There is only one class definition for a given class, so when a program is running, if something is static then there is only one of it.
A class definition will have its own varaibles (state), and will have its own methods (behavior).
The methods that a class definition has are called static methods. Program can execute a static method without first creating an object!
All other methods (those that are not static) must be part of an object. Example:
double angle = 30.0 * Math.PI / 180.0;
System.out.println(“cos(30) is “ + Math.cos(angle));
20
Strings and Object References
21
String literals
Strings are very common in programs, so Java optimizes their use. Usually if you need a string in your program you create it as follows.
String str = "String Literal"; A String created in this short-cut way is called a String literal.
22
String References as Parameters
A String can be a parameter to a method. Example 1:
String strA = “Lecturer”;
String strB = “Instructor”;
if ( strA.equals(strB) )
System.out.println(“They are equals”);
else
System.out.println(“They are different”);
Example 2:String answer = “yes”;
if ( answer.equals(“no”) )
System.out.println(“WELCOME BACK”);
else
System.out.println(“GOOD BYE”);
23
The null Value
A special value called null is assigned to an object reference variable when it does not refer to an object.
The value null is a special value that means "no object." null can be assigned to reference variables of any type.
» Examples:
String strA = null;
Point p = null;
You can test a reference variable if it refers to an object or not:
if (p == null)
System.out.println(“No object”);
24
Empty String
Empty String is a String object that contains no characters. It is defined as follows:
String strB = "";» A new String object with no characters will be created. StrB will refer to that
object.
Don’t confuse between null value and empty String.
25
Concatenation means joining two or more strings together. Java allows two strings to be concatenated using either of the
following:» concat() method of a String object
String first = “Ali”;
String last = “ Salem”;
String name = first.concat(last);
» ‘ + ’ OperatorString first = “Ali”;
String last = “ Salem”;
String name = frist + last;
String Concatenation
public String concat (String str)
26
Some String methods
We can also ask a string object its length by calling its length() method:
» Example:String greeting = “Salaam Shabaab”;
int count = greeting.length();
Frequently, we need to test if one string is the prefix of another. This can be done by using startsWith() method.
» Example:String answer = “Nothing”;
if ( answer.startsWith(“No”) )
System.out.println(“No respose”);
public boolean startsWith (String prefix)
public int length();
27
Some String methods
It is useful to convert a String to upper case or lower case
» Example:String answer = “Yes”;
String answer2 = answer.tolowerCase();
Another useful method of String is trim.
» Example:String data = “ 123 “;
String fixed;
fixed = data.trim();
String trim(); Removes leading and trailing white spaces.
String toLowerCase(); Returns the lower case equivalent of this string.
String toUpperCase(); Returns the lower case equivalent of this string.
28
Another special feature of Strings is that they are immutable. That is, once a string object is created, its content cannot be changed. Thus, all methods that appear to be modifying string objects are actually creating and returning new string objects. For example, consider the following:
String greeting = “Salaam”;greeting = greeting.concat(“ Shaabab”);
Instead of changing the greeting object, another object is created. The former is garbage collected.
The fact that Strings are immutable makes string processing very efficiently in Java.
Strings are Immutable
29
Temporary Objects Example 1:
» First: a temporary String object is created containing these characters.» Next: the toLowerCase() method of the temporary object is called. It creates a
second object with all lower case characters.» Finally: the reference to the second object is assigned to the reference variable d.
Example 2 (Cascading methods):
» How many temporary objects have been created?
What’s going wrong? System.out.println( answer.length().trim() );
String d = “JAVA COURSE”.toLowerCase().
String answer = “ Nothing ”;
if ( answer.trim().toUpperCase().startsWith(“NO”) )System.out.println(“Thank you.”);