MELJUN CORTES Java Lecture Working with Objects

43
Working with Working with Objects Objects how Java implements OOP how Java implements OOP MELJUN CORTES MELJUN CORTES MELJUN CORTES MELJUN CORTES

description

MELJUN CORTES Java Lecture Working with Objects

Transcript of MELJUN CORTES Java Lecture Working with Objects

Page 1: MELJUN CORTES Java Lecture Working with Objects

Working with Working with ObjectsObjects

how Java implements OOPhow Java implements OOP

MELJUN CORTESMELJUN CORTES

MELJUN CORTESMELJUN CORTES

Page 2: MELJUN CORTES Java Lecture Working with Objects

ContentsContents

I.I. Review: Datatypes & OOPReview: Datatypes & OOP

II.II. OOP in JavaOOP in JavaA.A. Object InstantiationObject Instantiation

B.B. ReferencesReferences

C.C. Garbage CollectionGarbage Collection

D.D. Calling Instance MembersCalling Instance Members

E.E. Parameter PassingParameter Passing

F.F. StaticsStatics

G.G. CastingCasting

H.H. Comparison OperatorsComparison Operators

I.I. Determining the Class of an ObjectDetermining the Class of an Object

Page 3: MELJUN CORTES Java Lecture Working with Objects

Review: DatatypesReview: Datatypes

Java has two kinds of datatypes:Java has two kinds of datatypes: PrimitivesPrimitives ObjectsObjects

Page 4: MELJUN CORTES Java Lecture Working with Objects

Review: DatatypesReview: Datatypes

Ideally, all datatypes should be objects, Ideally, all datatypes should be objects, but some compromise was made for but some compromise was made for performance.performance.

Page 5: MELJUN CORTES Java Lecture Working with Objects

Review: Classes and ObjectsReview: Classes and Objects

Class Class can be thought of as a template, a prototype or a blueprint can be thought of as a template, a prototype or a blueprint

of an objectof an object is the fundamental structure in object-oriented is the fundamental structure in object-oriented

programming programming

Two types of class members:Two types of class members: Attributes / Fields / PropertiesAttributes / Fields / Properties

specify the data types defined by the class Methods.Methods.

specify the operations

Page 6: MELJUN CORTES Java Lecture Working with Objects

Review: Classes and Review: Classes and ObjectsObjects

Object Object An object is an An object is an instanceinstance of a class. of a class. Each object has its own data, even if they’re of the Each object has its own data, even if they’re of the

same class.same class. An instance must be created before you can call An instance must be created before you can call

its members.its members.

Page 7: MELJUN CORTES Java Lecture Working with Objects

OOP in JavaOOP in Java

Java Fundamentals and Object-Oriented Java Fundamentals and Object-Oriented ProgrammingProgramming

The Complete Java Boot CampThe Complete Java Boot Camp

Page 8: MELJUN CORTES Java Lecture Working with Objects

Object InstantiationObject Instantiation

To create an object or an instance of a class, we To create an object or an instance of a class, we use the use the newnew operator. operator.

For example, if you want to create an instance of For example, if you want to create an instance of the class Integer, we write the following code:the class Integer, we write the following code:

BigDecimal salary = new BigDecimal(“2600.00”);

reference

“new” operator

constructordata type of

reference

Page 9: MELJUN CORTES Java Lecture Working with Objects

Object InstantiationObject Instantiation

The constructor The constructor A special method which instantiates an object, A special method which instantiates an object,

it has the same name as the class. Must be it has the same name as the class. Must be used with the “new” operator.used with the “new” operator.

Code for initialization of the object can be Code for initialization of the object can be found here. It can have initialization found here. It can have initialization parameters.parameters.

BigDecimal(“2600.00”);BigDecimal(“2600.00”);

Page 10: MELJUN CORTES Java Lecture Working with Objects

Object InstantiationObject Instantiation

The The newnew operator operator allocates a memory location for that object allocates a memory location for that object

and returns a and returns a referencereference of that memory of that memory location to you. location to you.

Page 11: MELJUN CORTES Java Lecture Working with Objects

ReferencesReferences

ReferenceReference Number pointing to a memory location.Number pointing to a memory location.

salary value = 2600.00

reference tothe BigDecimal

object

the BigDecimalobject

points to

Page 12: MELJUN CORTES Java Lecture Working with Objects

ReferencesReferences

More than one reference can point to the More than one reference can point to the same object. same object.

BigDecimal salary = new BigDecimal(“2600.00”);BigDecimal mySalary = salary;BigDecimal hisSalary = salary;

salary value = 2600.00

hisSalary

mySalary

Page 13: MELJUN CORTES Java Lecture Working with Objects

ReferencesReferences

A reference can also point to no object at A reference can also point to no object at all.all.

BigDecimal yourSalary = null;BigDecimal yourSalary = null;

yourSalary nullnull

Page 14: MELJUN CORTES Java Lecture Working with Objects

ReferencesReferences

Using Using finalfinal on a reference on a reference Prevents the reference from changing

final char[] array = {‘d’, ‘o’, ‘g’};

array ‘d’ ‘o’ ‘g’won’t point elsewhere

Page 15: MELJUN CORTES Java Lecture Working with Objects

ReferencesReferences

Using Using finalfinal on a reference on a reference Does not prevent the value of the object to

change.

array[1] = ‘i’;

array ‘d’ ‘i’ ‘g’won’t point elsewhere

Page 16: MELJUN CORTES Java Lecture Working with Objects

Garbage CollectionGarbage Collection

When there are no more references to an When there are no more references to an object, it becomes ready for garbage object, it becomes ready for garbage collection.collection.

garbage collector

Page 17: MELJUN CORTES Java Lecture Working with Objects

Garbage CollectionGarbage Collection

An object loses a reference when:An object loses a reference when: The reference goes out of scope.The reference goes out of scope. The reference is pointed to another object.The reference is pointed to another object. The reference is pointed to null.The reference is pointed to null.

if (a > b) { BigDecimal salary = new BigDecimal(“2600”);}// salary is now out of scope

Page 18: MELJUN CORTES Java Lecture Working with Objects

Garbage CollectionGarbage Collection

An object loses a reference when:An object loses a reference when: The reference goes out of scope.The reference goes out of scope. The reference is pointed to another object.The reference is pointed to another object. The reference is pointed to null.The reference is pointed to null.

BigDecimal salary = new BigDecimal(“2600.00”); ...salary = new BigDecimal(“3000.00”); ...salary = null;

Page 19: MELJUN CORTES Java Lecture Working with Objects

Calling Instance MembersCalling Instance Members

Once an object is instantiated, you can call Once an object is instantiated, you can call its members: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);

Page 20: MELJUN CORTES Java Lecture Working with Objects

Calling Instance MembersCalling Instance Members

Once an object is instantiated, you can call Once an object is instantiated, you can call its members:its members:

int[] numbers = {1, 2, 3, 4, 5};int lengthOfArray = numbers.length;System.out.println(“The length of”

+ “ my array is: ” + lengthOfArray);

Page 21: MELJUN CORTES Java Lecture Working with Objects

MethodsMethods

The following are characteristics of The following are characteristics of methods: methods: It can return one or no valuesIt can return one or no values It may accept as many parameters it needs or It may accept as many parameters it needs or

no parameter at all. Parameters are also called no parameter at all. Parameters are also called arguments.arguments.

After the method has finished execution, it After the method has finished execution, it goes back to the method that called it. goes back to the method that called it.

Page 22: MELJUN CORTES Java Lecture Working with Objects

Parameter PassingParameter Passing

Pass-by-ValuePass-by-Value when a pass-by-value occurs, the method when a pass-by-value occurs, the method

makes a copy of the value of the variable makes a copy of the value of the variable passed to the method. The method cannot passed to the method. The method cannot modify the original argument even if it modifies modify the original argument even if it modifies the parameters during calculations.the parameters during calculations.

all all primitive data typesprimitive data types when passed to a when passed to a method are pass-by-value.method are pass-by-value.

Page 23: MELJUN CORTES Java Lecture Working with Objects

Pass-by-ValuePass-by-Value

Page 24: MELJUN CORTES Java Lecture Working with Objects

Parameter PassingParameter Passing

Pass-by-ReferencePass-by-Reference When a pass-by-reference occurs, the When a pass-by-reference occurs, the reference to an reference to an

objectobject is passed to the calling method. This means is passed to the calling method. This means that, the method makes a copythat, the method makes a copy of the reference of the reference of the of the variable passed to the method.variable passed to the method.

Unlike in pass-by-value, Unlike in pass-by-value, the method can modify the the method can modify the actual object that the reference is pointing toactual object that the reference is pointing to, , since, although different references are used in the since, although different references are used in the methods, the location of the data they are pointing to methods, the location of the data they are pointing to is the same.is the same.

Page 25: MELJUN CORTES Java Lecture Working with Objects

Pass-by-ReferencePass-by-Reference

Page 26: MELJUN CORTES Java Lecture Working with Objects

Pass-by-ReferencePass-by-Reference

Page 27: MELJUN CORTES Java Lecture Working with Objects

Static MembersStatic Members

Static members Static members belong to the class as a wholebelong to the class as a whole, , not to a certain instance.not to a certain instance.

Members that can be invoked without Members that can be invoked without instantiating an object.instantiating an object.

Statics are part of Java’s non-OO nature (like Statics are part of Java’s non-OO nature (like primitives).primitives).

Static methods are distinguished from Static methods are distinguished from instance methods in a class definition by the instance methods in a class definition by the keyword keyword staticstatic..

Page 28: MELJUN CORTES Java Lecture Working with Objects

Static MembersStatic Members

To call a static method, just type:To call a static method, just type:

Classname.staticMethodName(params);

To call a static variable, just type:To call a static variable, just type:

Classname.staticVaribleName;

Page 29: MELJUN CORTES Java Lecture Working with Objects

Calling Static MembersCalling Static Members

Examples of static methods, we've used so Examples of static methods, we've used so far in our examples are, 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 );

Page 30: MELJUN CORTES Java Lecture Working with Objects

Calling Static MembersCalling Static Members

Examples of calling static variables: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 - 1int i = Integer.MAX_VALUE;

// Returns the file name separator for// operating system being used// “/” for UNIX and “\” for WindowsString fileNameSeparator = File.separator;

Page 31: MELJUN CORTES Java Lecture Working with Objects

Static MembersStatic Members

Static methods are usually found in “Utility” classes – Static methods are usually found in “Utility” classes – classes that just hold routines for other classes:classes that just hold routines for other classes:

Math.round(int a) The Math class holds various mathematical routines.The Math class holds various mathematical routines. The “round” method rounds a floating point primitive to an The “round” method rounds a floating point primitive to an

integer.integer.

Arrays.sort(int[] a) The Arrays class holds various routines to work on arrays.The Arrays class holds various routines to work on arrays. The “sort” method sorts an array in ascending order. The “sort” method sorts an array in ascending order.

Page 32: MELJUN CORTES Java Lecture Working with Objects

Static MembersStatic Members

Static variables are usually constants or environment Static variables are usually constants or environment properties.properties.

Integer.MAX_VALUE Returns the maximum value that the Java int data type can Returns the maximum value that the Java int data type can

hold, 2hold, 23131 – 1. – 1.

System.out Returns a PrintWriter to the standard output stream, usually Returns a PrintWriter to the standard output stream, usually

prints to console.prints to console.

File.separator Returns the file separator for the current operating system.Returns the file separator for the current operating system.

Page 33: MELJUN CORTES Java Lecture Working with Objects

Casting ObjectsCasting Objects

Instances of classes can be cast into Instances of classes can be cast into instances of other classes, with one instances of other classes, with one restriction:restriction: The source and destination The source and destination classes must be related by inheritance; classes must be related by inheritance; one class must be a subclass of the other.one class must be a subclass of the other.

Casting objects is analogous to converting Casting objects is analogous to converting a primitive value to a larger type, some a primitive value to a larger type, some objects might not need to be cast objects might not need to be cast explicitly. explicitly.

Page 34: MELJUN CORTES Java Lecture Working with Objects

Casting ObjectsCasting Objects

To cast, To cast,

(classname)object(classname)object

where,where, classnameclassname, , is the name of the destination class is the name of the destination class objectobject, , is a reference to the source objectis a reference to the source object

Page 35: MELJUN CORTES Java Lecture Working with Objects

Casting Objects ExampleCasting Objects Example

The following example casts an instance of the class The following example casts an instance of the class VicePresident to an instance of the class Employee; VicePresident to an instance of the class Employee; VicePresident is a subclass of Employee with more VicePresident is a subclass of Employee with more information, which here defines that the VicePresident has information, which here defines that the VicePresident has executive washroom privileges.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;

Page 36: MELJUN CORTES Java Lecture Working with Objects

Casting ObjectsCasting Objects

if you cast to a wrong type, JVM will throw if you cast to a wrong type, JVM will throw a “ClassCastException” (Exceptions will a “ClassCastException” (Exceptions will be discussed later.)be discussed later.)

Page 37: MELJUN CORTES Java Lecture Working with Objects

OperatorsOperators

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.

Page 38: MELJUN CORTES Java Lecture Working with Objects

Using Equality Operators with Using Equality Operators with ObjectsObjects

Example:Example:

Object o1 = new Object();Object o1 = new Object();

Object o2 = o1;Object o2 = o1;

o1 == o2o1 == o2 true true

Page 39: MELJUN CORTES Java Lecture Working with Objects

Using Equality Operators with Using Equality Operators with ObjectsObjects

Example:Example:

Object o1 = new Object();Object o1 = new Object();

Object o2 = new Object();Object o2 = new Object();

o1 == o2o1 == o2 false false

Page 40: MELJUN CORTES Java Lecture Working with Objects

Want to find out what an object's class is? Here's Want to find out what an object's class is? Here's the way to do it.the way to do it.

Suppose we have the following object:Suppose we have the following object:

SomeClassName key = new SomeClassName();

Now, we'll discuss two ways to know the type of Now, we'll discuss two ways to know the type of the object pointed to by the reference the object pointed to by the reference key..

Determining the Class of an Determining the Class of an ObjectObject

Page 41: MELJUN CORTES Java Lecture Working with Objects

getClass() methodgetClass() 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();

Page 42: MELJUN CORTES Java Lecture Working with Objects

instanceOf operatorinstanceOf 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; // trueObject pt = new Point(10, 10);boolean ex2 = pt instanceof String; // false

Page 43: MELJUN CORTES Java Lecture Working with Objects

The EndThe End

Java Fundamentals and Object-Java Fundamentals and Object-Oriented ProgrammingOriented Programming

The Complete Java Boot CampThe Complete Java Boot Camp