Java: Objects and Object References


Published on

Sub: Java Topic: Objects and Object References Slide number: 8 Presented by: Mahbubul Islam (MMI) Lecturer, Dept. of CSE University of Rajshahi

Published in: Education, Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Java: Objects and Object References

  1. 1. Objects and Object References
  2. 2. What is an Object? <ul><li>Think about the things in the world that are objects? </li></ul><ul><ul><li>A pen is an object. </li></ul></ul><ul><ul><li>A computer keyboard is an object. </li></ul></ul><ul><ul><li>Bank account is an object </li></ul></ul><ul><ul><li>The class room is an object </li></ul></ul><ul><li>So, what all objects have in common? </li></ul><ul><ul><li>An object has identity (it acts as a single whole). </li></ul></ul><ul><ul><li>An object has state (it has various properties, which might change). </li></ul></ul><ul><ul><li>An object has behavior (it can do things and can have things done to it). </li></ul></ul><ul><ul><li>Example: </li></ul></ul><ul><ul><ul><li>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.) </li></ul></ul></ul>
  3. 3. Software objects <ul><li>It is convenient to have &quot;software objects&quot; that are similar to &quot;real world objects.&quot; This makes the program and its computation easier to think about. </li></ul><ul><li>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. </li></ul><ul><ul><li>Software objects have identity because each is a separate chunk of memory . </li></ul></ul><ul><ul><li>Software objects have state. Some of the memory that makes a software object is used for variables which contain values. </li></ul></ul><ul><ul><li>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 &quot;do things.&quot; The object does something when one of its method runs. </li></ul></ul><ul><li>Both variables and methods are called “ members ” of the object. </li></ul>Variables balance interest rate owner Methods deposit() withdraw() charge() Bank account Chunk of memory
  4. 4. Using a Class to make Objects <ul><li>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. </li></ul><ul><li>Different cookies may have different characteristics, even though they follow the same basic pattern. </li></ul><ul><li>Cookies can be created. And cookies can be destroyed (just ask Cookie Monster). But destroying cookies does not affect the cookie cutter. </li></ul><ul><li>To create an object, there needs to be a description of it. A Class is a description of a kind of object. </li></ul>
  5. 5. <ul><li>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 . </li></ul><ul><li>Once the object has been created (with the new operator). The variable str1 is used to refer to this object. </li></ul><ul><li>Java uses &quot;dot notation&quot; to access any of its members as follows: </li></ul><ul><li>referenceToAnObject . memberOfObject </li></ul><ul><li>Method names have &quot; () &quot; at their end. Often there is additional information inside the &quot; () &quot;, but they are required even if they contain nothing. </li></ul>Example Program 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 ( &quot;Salam Shabaab&quot; ); //create an object of type String len = str1 . length(); // invoke the object's method length() System . out . println( &quot;The string is &quot; + len + &quot; characters long&quot; ); } }
  6. 6. Constructors <ul><li>A constructor has the same name as the class. The line from the above program </li></ul><ul><ul><ul><ul><li>str1 = new String(&quot;Salam Shabaab&quot;); </li></ul></ul></ul></ul><ul><li>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. </li></ul><ul><li>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 &quot;Salam Shabaab&quot; (not including the quote marks) are stored in the new object. </li></ul><ul><li>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. </li></ul>
  7. 7. Primitive data types & Objects <ul><li>In Java, a piece of data either is of a primitive data type or is an object data type. </li></ul><ul><li>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. </li></ul><ul><li>A programmer may define a class using Java, or may use predefined classes that come in class libraries (like String). </li></ul>Primitive Data Objects int long float double char boolean String Applet Graphics
  8. 8. Object References <ul><li>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. </li></ul><ul><li>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. </li></ul><ul><li>In Java, there are only primitive variables and object reference variables, and each contains a specific kind of information: </li></ul>Kind of Variable Information it Contains When on the left of &quot;=&quot; 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. 9. Object References - Examples <ul><li>Example of two objects and two reference variables: </li></ul><ul><li>Example of one object and two reference variables </li></ul>String strA = new String (“Java”); String strB = new String (“C++”); String strA = new String (“Java”); String strB = strA strB JAVA strA C++ strB JAVA strA
  10. 10. Equality of Reference Variable Contents <ul><li>The == operator does NOT look at objects!   It only looks at references (information about where an object is located.) </li></ul>strA == strB is true strA == strB is false srtA.equals(strB) is true strA.equals(strB) is true
  11. 11. Using Objects and Classes
  12. 12. The Class Point <ul><li>A 2D geometrical point has two values that describe the location of the point in xy-plane. </li></ul><ul><li>So, it’s better to think of a point as a single &quot;thing&quot; (not as two separate things.) </li></ul><ul><li>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. </li></ul>
  13. 13. The Class Point Description <ul><li>public class java.awt.Point </li></ul><ul><li>// Fields </li></ul><ul><li>int x; </li></ul><ul><li>int y; </li></ul><ul><li>// Constructors </li></ul><ul><li>Point(); // creates a point at (0,0) </li></ul><ul><li>Point(int x, int y); // creates a point at (x,y) </li></ul><ul><li>Point( Point pt ); // creates a point at the location given in pt </li></ul><ul><li>// Methods </li></ul><ul><li>boolean equals(Object obj); // checks if two point objects hold equivalent data </li></ul><ul><li>void move(int x, int y); // changes the (x,y) data of a point object </li></ul><ul><li>String toString(); // returns character data that can be printed </li></ul><ul><li>(I've left out some methods we won't be using.) </li></ul>
  14. 14. Using the Class Point <ul><li>To create an object point, we may write the following code: </li></ul><ul><ul><li>Point a; </li></ul></ul><ul><ul><li>a = new Point(); </li></ul></ul><ul><li>The previous code can be rewritten as follow: </li></ul><ul><ul><ul><li>Point a = new Point(); </li></ul></ul></ul><ul><li>Can you create a point at location (12, 7) ? </li></ul><ul><li>Can you write a code to use the last constructor? </li></ul>a a 0, 0 move() equals() toString() // Constructors Point(); Point(int x, int y); Point( Point pt );
  15. 15. toString() method <ul><li>The method toString() can be used to create a printable String for a given object. </li></ul><ul><li>public String toString(); </li></ul><ul><li>The toString() method does not require any parameters. (it’s called parameter-less method.) </li></ul><ul><ul><ul><li>Point a = new Point(12, 7); </li></ul></ul></ul><ul><ul><ul><li>String str; </li></ul></ul></ul><ul><ul><ul><li>str = a.toString(); </li></ul></ul></ul><ul><ul><ul><li>System.out.println(str); </li></ul></ul></ul><ul><li>The previous example can be modified as follow: </li></ul><ul><ul><ul><li>Point a = new Point(12, 7); </li></ul></ul></ul><ul><ul><ul><li>System.out.println(a.toString()); </li></ul></ul></ul><ul><li>When toString() is provided in class definition, it is automatically invoked when object name is used where String object is expected. </li></ul><ul><ul><ul><li>Example: System.out.println( a ); </li></ul></ul></ul>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. 16. Equivalent Data and Alias <ul><li>Example 1: </li></ul><ul><ul><ul><li>Point pt1 = new Point(5, 9); </li></ul></ul></ul><ul><ul><ul><li>Point pt2 = new Point(5, 9); </li></ul></ul></ul><ul><ul><li>The variable pt1 and the variable pt2 are referring to different objects, but both objects have equivalent data. </li></ul></ul><ul><li>Example 2: </li></ul><ul><ul><ul><li>Point pt3 = new Point(5, 9); </li></ul></ul></ul><ul><ul><ul><li>Point pt4 = pt3; </li></ul></ul></ul><ul><ul><li>The variable pt3 and the variable pt4 are referring to the same object. So, each reference variables is said to be an alias . </li></ul></ul><ul><li>equals() method is used to test if the two objects contain equivalent data. </li></ul><ul><ul><ul><li>Example: if ( pt1.equals(pt2) ) ... </li></ul></ul></ul><ul><li>== operator is used to test if the two reference variables refer to the same object. </li></ul><ul><ul><ul><li>Example: if ( pt3 == pt4 ) ... </li></ul></ul></ul>
  17. 17. move() Method <ul><li>Is used to change the x and the y values inside a Point object. </li></ul><ul><li>The description of the method move() inside class Point: </li></ul><ul><li>public void move( int x, int y ); </li></ul><ul><ul><li>The modifier public means that it can be used anywhere in your program </li></ul></ul><ul><ul><li>void means that it does not return a value. </li></ul></ul><ul><ul><li>( 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. </li></ul></ul><ul><li>Example: </li></ul><ul><ul><ul><li>Point a = new Point(12, 7); </li></ul></ul></ul><ul><ul><ul><li>System.out.println( a ); </li></ul></ul></ul><ul><ul><ul><li>a.move(10, 13); </li></ul></ul></ul><ul><ul><ul><li>System.out.prinltn( a ); </li></ul></ul></ul><ul><li>You can put expressions into parameter lists as long as the expression evaluates to the type expected by the method. </li></ul><ul><ul><li>Example: </li></ul></ul><ul><ul><ul><li>a.move(20-12, 30*3-45); // equivalent to a.move(8,45) </li></ul></ul></ul>java.awt.Point[x=12,y=7] java.awt.Point[x=10,y=13]
  18. 18. Type casting <ul><li>A cast is an explicit conversion of a value from its current type to another type. </li></ul><ul><li>The syntax for a cast is: (requiredType) (expression) </li></ul><ul><ul><li>Example: </li></ul></ul><ul><ul><ul><li>Point pt = new Point(); </li></ul></ul></ul><ul><ul><ul><li>short a = 13; </li></ul></ul></ul><ul><ul><ul><li>a.move(a, (int)14.6359 ); </li></ul></ul></ul>int long float double loss of information <ul><li>Casting is required when converting to a required type will result in loss of information. </li></ul><ul><li>However, when a conversion from one type to another type can be done without loss of information, the compiler will do it automatically </li></ul>
  19. 19. Static Methods <ul><li>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. </li></ul><ul><li>A class definition will have its own varaibles (state), and will have its own methods (behavior). </li></ul><ul><li>The methods that a class definition has are called static methods . </li></ul><ul><li>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. </li></ul><ul><li>Example: </li></ul><ul><ul><li>double angle = 30.0 * Math.PI / 180.0; </li></ul></ul><ul><ul><li>System.out.println(“cos(30) is “ + Math.cos(angle)); </li></ul></ul>
  20. 20. Strings and Object References
  21. 21. String literals <ul><li>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. </li></ul><ul><li>String str = &quot;String Literal&quot;; </li></ul><ul><li>A String created in this short-cut way is called a String literal. </li></ul>
  22. 22. String References as Parameters <ul><li>A String can be a parameter to a method. </li></ul><ul><li>Example 1: </li></ul><ul><ul><ul><li>String strA = “Lecturer”; </li></ul></ul></ul><ul><ul><ul><li>String strB = “Instructor”; </li></ul></ul></ul><ul><ul><ul><li>if ( strA.equals(strB) ) </li></ul></ul></ul><ul><ul><ul><li>System.out.println(“They are equals”); </li></ul></ul></ul><ul><ul><ul><li>else </li></ul></ul></ul><ul><ul><ul><li>System.out.println(“They are different”); </li></ul></ul></ul><ul><li>Example 2: </li></ul><ul><ul><ul><li>String answer = “yes”; </li></ul></ul></ul><ul><ul><ul><li>if ( answer.equals(“no”) ) </li></ul></ul></ul><ul><ul><ul><li>System.out.println(“WELCOME BACK”); </li></ul></ul></ul><ul><ul><ul><li>else </li></ul></ul></ul><ul><ul><ul><li>System.out.println(“GOOD BYE”); </li></ul></ul></ul>
  23. 23. The null Value <ul><li>A special value called null is assigned to an object reference variable when it does not refer to an object. </li></ul><ul><li>The value null is a special value that means &quot;no object.&quot; </li></ul><ul><li>null can be assigned to reference variables of any type. </li></ul><ul><ul><li>Examples: </li></ul></ul><ul><ul><ul><li>String strA = null; </li></ul></ul></ul><ul><ul><ul><li>Point p = null; </li></ul></ul></ul><ul><li>You can test a reference variable if it refers to an object or not: </li></ul><ul><ul><li>if (p == null) </li></ul></ul><ul><ul><li>System.out.println(“No object”); </li></ul></ul>
  24. 24. Empty String <ul><li>Empty String is a String object that contains no characters. It is defined as follows: </li></ul><ul><li>String strB = &quot;&quot;; </li></ul><ul><ul><li>A new String object with no characters will be created. StrB will refer to that object. </li></ul></ul><ul><li>Don’t confuse between null value and empty String. </li></ul>
  25. 25. <ul><li>Concatenation means joining two or more strings together. </li></ul><ul><li>Java allows two strings to be concatenated using either of the following: </li></ul><ul><ul><li>concat() method of a String object </li></ul></ul><ul><ul><ul><li>String first = “Ali”; </li></ul></ul></ul><ul><ul><ul><li>String last = “ Salem”; </li></ul></ul></ul><ul><ul><ul><li>String name = first.concat(last); </li></ul></ul></ul><ul><ul><li>‘ + ’ Operator </li></ul></ul><ul><ul><ul><li>String first = “Ali”; </li></ul></ul></ul><ul><ul><ul><li>String last = “ Salem”; </li></ul></ul></ul><ul><ul><ul><li>String name = frist + last; </li></ul></ul></ul>String Concatenation public String concat (String str)
  26. 26. Some String methods <ul><li>We can also ask a string object its length by calling its length() method: </li></ul><ul><ul><li>Example: </li></ul></ul><ul><ul><ul><li>String greeting = “Salaam Shabaab”; </li></ul></ul></ul><ul><ul><ul><li>int count = greeting.length(); </li></ul></ul></ul><ul><li>Frequently, we need to test if one string is the prefix of another. This can be done by using startsWith() method. </li></ul><ul><ul><li>Example: </li></ul></ul><ul><ul><ul><li>String answer = “Nothing”; </li></ul></ul></ul><ul><ul><ul><li>if ( answer.startsWith(“No”) ) </li></ul></ul></ul><ul><ul><ul><li>System.out.println(“No respose”); </li></ul></ul></ul>public boolean startsWith (String prefix) public int length ();
  27. 27. Some String methods <ul><li>It is useful to convert a String to upper case or lower case </li></ul><ul><ul><li>Example: </li></ul></ul><ul><ul><ul><li>String answer = “Yes”; </li></ul></ul></ul><ul><ul><ul><li>String answer2 = answer.tolowerCase(); </li></ul></ul></ul><ul><li>Another useful method of String is trim. </li></ul><ul><ul><li>Example: </li></ul></ul><ul><ul><ul><li>String data = “ 123 “; </li></ul></ul></ul><ul><ul><ul><li>String fixed; </li></ul></ul></ul><ul><ul><ul><li>fixed = data.trim(); </li></ul></ul></ul>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. 28. Strings are Immutable <ul><li>Another special feature of Strings is that they are immutable. That is, once a string object </li></ul><ul><li>is created, its content cannot be changed. </li></ul><ul><li>Thus, all methods that appear to be modifying string objects are actually creating and </li></ul><ul><li>returning new string objects. </li></ul><ul><li>For example, consider the following: </li></ul><ul><li>String greeting = “Salaam”; </li></ul><ul><li>greeting = greeting.concat(“ Shaabab”); </li></ul><ul><li>Instead of changing the greeting object, another object is created. The former is garbage collected. </li></ul><ul><li>The fact that Strings are immutable makes string processing very efficiently in Java. </li></ul>
  29. 29. Temporary Objects <ul><li>Example 1: </li></ul><ul><ul><li>First: a temporary String object is created containing these characters. </li></ul></ul><ul><ul><li>Next: the toLowerCase() method of the temporary object is called. It creates a second object with all lower case characters. </li></ul></ul><ul><ul><li>Finally: the reference to the second object is assigned to the reference variable d. </li></ul></ul><ul><li>Example 2 (Cascading methods): </li></ul><ul><ul><li>How many temporary objects have been created? </li></ul></ul><ul><li>What’s going wrong? </li></ul><ul><ul><li>System.out.println( answer.length().trim() ); </li></ul></ul>String d = “JAVA COURSE”.toLowerCase(). String answer = “ Nothing ”; if ( answer.trim().toUpperCase().startsWith(“NO”) ) System.out.println(“Thank you.”);