MELJUN CORTES Java Lecture Working with Objects


Published on

MELJUN CORTES Java Lecture Working with Objects

Published in: Technology
  • Be the first to comment

  • Be the first to like this

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

No notes for slide
  • The last statement is not exactly true for Java. In Java, there is such a thing as “static” methods and “static” variables, which can be called even without instantiating an object. This is part of Java’s non-OOP nature. More on this a little later.
  • You can think of the garbage collector as something like Pacman, he goes around eating things nobody’s using anymore.
  • You can do more things with the Class object by using Java’s Reflection API (java.lang.reflect), but that’s a much more advanced topic, not covered in this boot camp.
  • MELJUN CORTES Java Lecture Working with Objects

    1. 1. Working with Objects MELJUN CORTES how Java implements OOP MELJUN CORTES
    2. 2. Contents Review: Datatypes & OOP OOP in Java I. II. A. B. C. D. E. F. G. H. I. Object Instantiation References Garbage Collection Calling Instance Members Parameter Passing Statics Casting Comparison Operators Determining the Class of an Object
    3. 3. Review: Datatypes  Java has two kinds of datatypes:  Primitives  Objects
    4. 4. Review: Datatypes  Ideally, all datatypes should be objects, but some compromise was made for performance.
    5. 5. Review: Classes and Objects  Class  can be thought of as a template, a prototype or a blueprint of an object  is the fundamental structure in object-oriented programming  Two types of class members:  Attributes / Fields / Properties   specify the data types defined by the class Methods.  specify the operations
    6. 6. Review: Classes and Objects  Object An object is an instance of a class.  Each object has its own data, even if they’re of the same class.  An instance must be created before you can call its members. 
    7. 7. OOP in Java Java Fundamentals and Object-Oriented Programming The Complete Java Boot Camp
    8. 8. Object Instantiation  To create an object or an instance of a class, we use the new operator.  For example, if you want to create an instance of the class Integer, we write the following code: BigDecimal salary = new BigDecimal(“2600.00”); data type of reference reference “new” operator constructor
    9. 9. Object Instantiation The constructor A special method which instantiates an object, it has the same name as the class. Must be used with the “new” operator.  Code for initialization of the object can be found here. It can have initialization parameters.  BigDecimal(“2600.00”);
    10. 10. Object Instantiation  The new operator  allocates a memory location for that object and returns a reference of that memory location to you.
    11. 11. References Reference  Number pointing to a memory location. salary reference to the BigDecimal object points to value = 2600.00 the BigDecimal object
    12. 12. References  More than one reference can point to the same object. BigDecimal salary = new BigDecimal(“2600.00”); BigDecimal mySalary = salary; BigDecimal hisSalary = salary; mySalary salary value = 2600.00 hisSalary
    13. 13. References  A reference can also point to no object at all. BigDecimal yourSalary = null; yourSalary null null
    14. 14. References Using final on a reference  Prevents the reference from changing final char[] array = {‘d’, ‘o’, ‘g’}; array won’t point elsewhere ‘d’ ‘o’ ‘g’
    15. 15. References Using final on a reference  Does not prevent the value of the object to change. array[1] = ‘i’; array won’t point elsewhere ‘d’ ‘i’ ‘g’
    16. 16. Garbage Collection  When there are no more references to an object, it becomes ready for garbage collection. garbage collector
    17. 17. Garbage Collection  An object loses a reference when: The reference goes out of scope.  The reference is pointed to another object.  The reference is pointed to null.  if (a > b) { BigDecimal salary = new BigDecimal(“2600”); } // salary is now out of scope
    18. 18. Garbage Collection  An object loses a reference when: The reference goes out of scope.  The reference is pointed to another object.  The reference is pointed to null.  BigDecimal salary = new BigDecimal(“2600.00”); ... salary = new BigDecimal(“3000.00”); ... salary = null;
    19. 19. Calling Instance Members  Once an object is instantiated, you can call its members: BigDecimal salary = new BigDecimal(“2600.00”); BigDecimal tax = new BigDecimal(“0.32”); BigDecimal deduction = salary.multiply(tax); BigDecimal takeHome = salary.subtract(deduction); System.out.println(“my take-home pay: ” + takeHome);
    20. 20. Calling Instance Members  Once an object is instantiated, you can call its members: int[] numbers = {1, 2, 3, 4, 5}; int lengthOfArray = numbers.length; System.out.println(“The length of” + “ my array is: ” + lengthOfArray);
    21. 21. Methods  The following are characteristics of methods: It can return one or no values  It may accept as many parameters it needs or no parameter at all. Parameters are also called arguments.  After the method has finished execution, it goes back to the method that called it. 
    22. 22. Parameter Passing  Pass-by-Value when a pass-by-value occurs, the method makes a copy of the value of the variable passed to the method. The method cannot modify the original argument even if it modifies the parameters during calculations.  all primitive data types when passed to a method are pass-by-value. 
    23. 23. Pass-by-Value
    24. 24. Parameter Passing  Pass-by-Reference   When a pass-by-reference occurs, the reference to an object is passed to the calling method. This means that, the method makes a copy of the reference of the variable passed to the method. Unlike in pass-by-value, the method can modify the actual object that the reference is pointing to , since, although different references are used in the methods, the location of the data they are pointing to is the same.
    25. 25. Pass-by-Reference
    26. 26. Pass-by-Reference
    27. 27. Static Members  Static members belong to the class as a whole, not to a certain instance.  Members that can be invoked without instantiating an object.  Statics are part of Java’s non-OO nature (like primitives).  Static methods are distinguished from instance methods in a class definition by the keyword static.
    28. 28. Static Members  To call a static method, just type: Classname.staticMethodName(params);  To call a static variable, just type: Classname.staticVaribleName;
    29. 29. Calling Static Members  Examples of static methods, we've used so far in our examples are, //prints data to screen System.out.println(“Hello world”); //converts the String 10, to an integer int i = Integer.parseInt(“10”); //Returns a String representation //of the integer argument as an //unsigned integer base 16 String hexEquivalent = Integer.toHexString( 10 );
    30. 30. Calling Static Members  Examples of calling static variables: // the “standard” output stream, typically // prints output to console PrintStream out = System.out; // get the maximum possible value for // the Java int data type, 231 - 1 int i = Integer.MAX_VALUE; // Returns the file name separator for // operating system being used // “/” for UNIX and “” for Windows String fileNameSeparator = File.separator;
    31. 31. Static Members  Static methods are usually found in “Utility” classes – classes that just hold routines for other classes: Math.round(int a)   The Math class holds various mathematical routines. The “round” method rounds a floating point primitive to an integer. Arrays.sort(int[] a)   The Arrays class holds various routines to work on arrays. The “sort” method sorts an array in ascending order.
    32. 32. Static Members  Static variables are usually constants or environment properties. Integer.MAX_VALUE  Returns the maximum value that the Java int data type can hold, 231 – 1. System.out  Returns a PrintWriter to the standard output stream, usually prints to console. File.separator  Returns the file separator for the current operating system.
    33. 33. Casting Objects  Instances of classes can be cast into instances of other classes, with one restriction: The source and destination classes must be related by inheritance; one class must be a subclass of the other.  Casting objects is analogous to converting a primitive value to a larger type, some objects might not need to be cast explicitly.
    34. 34. Casting Objects  To cast, (classname)object where, classname, is the name of the destination class object, is a reference to the source object
    35. 35. Casting Objects Example  The following example casts an instance of the class VicePresident to an instance of the class Employee; VicePresident is a subclass of Employee with more information, which here defines that the VicePresident has executive washroom privileges. Employee emp = new Employee(); VicePresident veep = new VicePresident(); // no cast needed for upward use emp = veep; // must cast explicitlyCasting veep = (VicePresident)emp;
    36. 36. Casting Objects  if you cast to a wrong type, JVM will throw a “ClassCastException” (Exceptions will be discussed later.)
    37. 37. Operators  With the exception of the String class, all arithmetic and logical operators cannot be used with objects.  == and != work with objects, but they only test if two references are pointing to the same instance.  No other comparison operators work with objects.
    38. 38. Using Equality Operators with Objects  Example: Object o1 Object o2 o1 == o2 = new Object(); = o1;  true
    39. 39. Using Equality Operators with Objects  Example: Object o1 = new Object(); Object o2 = new Object(); o1 == o2  false
    40. 40. Determining the Class of an Object  Want to find out what an object's class is? Here's the way to do it.  Suppose we have the following object: SomeClassNamekey = new SomeClassName(); Now, we'll discuss two ways to know the type of the object pointed to by the reference key.
    41. 41. getClass() method  The getClass() method returns a Class object (where Class is itself a class) that has a method called getName().  In turn, getName() returns a string representing the name of the class. String name = key.getClass().getName();
    42. 42. instanceOf operator  The instanceOf has two operands: a reference to an object on the left and a class name on the right.  The expression returns true or false based on whether the object is an instance of the named class or any of that class's subclasses. boolean ex1 = "Texas" instanceof String; // true Object pt = new Point(10, 10); boolean ex2 = pt instanceof String; // false
    43. 43. The End Java Fundamentals and ObjectOriented Programming The Complete Java Boot Camp