java built in classes

68
1 Working with Java Working with Java Classes Classes

Upload: clarence-irudaya-samy

Post on 04-Jun-2018

235 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 1/68

1

Working with JavaWorking with Java

ClassesClasses

Page 2: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 2/68

2

Objectives

 At the end of the lesson, the student should be able to:

● Explain object-oriented programming and some of itsconcepts

● Differentiate between classes and objects

● Differentiate between instance variables/methods andclass(static variables/methods

● Explain what methods are and how to call and pass

parameters to methods

● !dentif" the scope of a variable

● #ast primitive data t"pes and objects

#ompare objects and determine the class of an objects

Page 3: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 3/68

3

 Brief IntroductionBrief Introductionon OOPon OOP

Page 4: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 4/68

4

Introduction to OOP

● $bject-$riented programming or $$%

 – &evolves around the concept of objects as the basic elementsof "our programs'

 – hese objects are characteri)ed b" their properties and

behaviors'

Page 5: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 5/68

5

Introduction to OOP

● Example of objects

objects in the ph"sical world can easil" be modeled assoftware objects using the properties as data and thebehaviors as methods

Page 6: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 6/68

6

Encapsulation

● Encapsulation

 – he scheme of hiding implementation details of a class'

 – he caller of the class does not need to *now the

implementation details of a class – he implementation can change without affecting the caller of

the class

Page 7: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 7/68

7

 Classes andClasses and

Objects (ObjectObjects (ObjectInstances)Instances)

Page 8: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 8/68

8

Classes and Objects

● #lass

 – can be thought of as a template, a protot"pe or a blueprint of anobject

 – is the fundamental structure in object-oriented programming

● wo t"pes of class members:

 – +ields (properties, variables

● specif" the data t"pes defined b" the class

 – ethods (behavior

● specif" the operations

Page 9: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 9/68

9

Classes and Objects

● $bject

 –  An object is an instance of a class - we will call it object instance

 – he propert" values of an object instance is different from theones of other object instances of a same class

 – $bject instances of a same class share the same behavior(methods

Page 10: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 10/68

10

Classes and Objects

● o differentiate between classes and objects, let usdiscuss an example:

Page 11: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 11/68

11

Classes and Objects

● #lasses provide the benefit of reusabilit"'

● oftware programmers can use a class over and over

again to create man" object instances'

Page 12: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 12/68

12

 Creation of ObjectCreation of Object

Instances withInstances with“new ke!word“new ke!word

Page 13: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 13/68

13

Creation of Object Instance

● o create an object instance of a class, we use the new operator'

● +or example, if "ou want to create an instance of theclass tring, we write the following code,

String str2 = new String(“Hello world!”);or also e.uivalent to,

String str2 = "Hello";

● tring class is a special (and onl" class "ou can create aninstance without using new *e"word as shown above 

Page 14: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 14/68

14

Creation of Object Instance

● he new operator

 – allocates a memor" for that object and returns a reference ofthat memor" location to "ou'

 –

hen "ou create an object, "ou actuall" invo*e the class0constructor'

● he constructor

 – is a method where "ou place all the initiali)ations, it has the

same name as the class'

Page 15: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 15/68

15

 "ethods"ethods

(Instance #ethods $(Instance #ethods $%tatic #ethods)%tatic #ethods)

Page 16: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 16/68

Page 17: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 17/68

17

Why Use Methods?

● ethods contain behavior of a class (business logic

 – he heart of effective problem solving is in problemdecomposition'

 –

e can do this in 1ava b" creating methods to solve a specificpart of the problem'

 – a*ing a problem and brea*ing it into small, manageablepieces is critical to writing large programs'

Page 18: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 18/68

18

Two Types of Methods

● !nstance (non-static methods

 – hould be called after object instance is created

 – ore common than static methods

● tatic methods – hould be called in the form of 2#lass3ame4'2method3ame4

Page 19: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 19/68

Page 20: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 20/68

20

Callin Instance Methods

● 6et0s ta*e two sample methods found in the tring class

Page 21: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 21/68

21

Callin Instance Methods

● Example

String str1 = "Hello";

char x = str1.charAt(0); //will return the character H

//and store it to variable x

String str2 = "hello";

//this will return a boolean value true

 boolean result = str1.equalsIgnoreCase( str2 );

Page 22: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 22/68

22

Callin $tatic Methods

● tatic methods

 – methods that can be invo*ed without instantiating a class(means without invo*ing the new *e"word'

 – tatic methods belong to the class as a whole and not to a

certain instance (or object of a class' – tatic methods are distinguished from instance methods in a

class definition b" the *e"word static'

● o call a static method, just t"pe,

Classname.staticMethodName(params); 

Page 23: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 23/68

23

Callin $tatic Methods

● Examples of static methods, we0ve used so far in ourexamples are,

//prints data to screenSystem.out.println(“Hello world”);

//converts the String 10 to an integerint i ! "nteger.parse"nt(“10”);

//#eturns a String representation o$ the integer argument as an//unsigned integer %ase 1&String he'uivalent ! "nteger.toHe'String( 10 );

Page 24: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 24/68

24

 Para#eter PassingPara#eter Passing

(Pass&b!&value $(Pass&b!&value $Pass&b!&reference)Pass&b!&reference)

Page 25: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 25/68

25

Para%eter Passin

● %ass-b"-7alue

 – when a pass-b"-value occurs, the method ma*es a cop" ofthe value of the variable passed to the method' he methodcannot accidentall" modif" the original argument even if it

modifies the parameters during calculations'

 – all primitive data t"pes when passed to a method are pass-b"-value'

Page 26: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 26/68

26

Pass"by"&alue

Page 27: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 27/68

27

Para%eter Passin

● %ass-b"-&eference

 – hen a pass-b"-reference occurs, the reference to an objectis passed to the calling method' his means that, the methodma*es a cop" of the reference of the variable passed to the

method'

 – 8owever, unli*e in pass-b"-value, the method can modif" theactual object that the reference is pointing to, since, althoughdifferent references are used in the methods, the location ofthe data the" are pointing to is the same'

Page 28: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 28/68

28

Pass"by"'eference

Page 29: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 29/68

29

Pass"by"'eference

Page 30: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 30/68

30

 'ariables (ields'ariables (ieldsPro*erties)Pro*erties)

Page 31: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 31/68

31

&ariables

● Data identifiers

●  Are used to refer to specific values that are generatedin a program--values that "ou want to *eep around

Page 32: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 32/68

32

Three Types of &ariables● 6ocal (automatic variable

 – declared within a method bod"

 – visible onl" within a method bod"

 – maintained in a stac*

● !nstance variable

 – declared inside a class bod" but outside of an" method bodies

 – per each object instance

 – cannot be referenced from static context

#lass (static variable – declared inside a class bod" but outside of an" method bodies

 – prepended with the static modifier 

 – per each class

 – shared b" all object instances

Page 33: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 33/68

33

 %co*e of a 'ariable%co*e of a 'ariable

Page 34: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 34/68

34

$cope of a &ariable

● he scope

 – determines where in the program the variable is accessible'

 – determines the lifetime of a variable or how long the variablecan exist in memor"'

 – he scope is determined b" where the variable declaration isplaced in the program'

● o simplif" things, just thin* of the scope as an"thingbetween the curl" braces 9'''' he outer curl" bracesare called the outer bloc*s, and the inner curl" bracesare called inner bloc*s'

Page 35: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 35/68

35

$cope of a &ariable

●  A variable0s scope is

 – inside the bloc* where it is declared, starting from the pointwhere it is declared

Page 36: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 36/68

36

E(a%ple )

Page 37: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 37/68

Page 38: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 38/68

38

E(a%ple *

Page 39: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 39/68

39

E(a%ple *

● !n the main method, the scopes of the variables are,

 – ages24 - scope A

 – i in < - scope <

 – i in # = scope #

● !n the test method, the scopes of the variables are,

 – arr24 - scope D

 – i in E - scope E

Page 40: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 40/68

40

$cope of a &ariable

● hen declaring variables, onl" one variable with agiven identifier or name can be declared in a scope'

● hat means that if "ou have the following declaration,

{

int test = 10;

int test = 20;

}

"our compiler will generate an error  since "ou shouldhave uni.ue names for "our variables in one bloc*'

Page 41: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 41/68

41

$cope of a &ariable

● 8owever, "ou can have two variables of the samename, if the" are not declared in the same bloc*' +orexample,

int test = 0;System.out.print( test ); // prints 0

 

//..some code here

if ( x == 2) {

int test = 20;

System.out.print( test );// prints 20}

System.out.print( test ); // prints 0

Page 42: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 42/68

42

$cope of &ariables

● 6ocal (automatic variable

 – onl" valid from the line the" are declared on until the closingcurl" brace of the method or code bloc* within which the" aredeclared

 – most limited scope

● !nstance variable

 – valid as long as the object instance is alive

● #lass (static variable

 – in scope from the point the class is loaded into the 17 untilthe the class is unloaded' #lass are loaded into the 17 thefirst time the class is referenced

Page 43: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 43/68

43

Codin +uidelines

●  Avoid having variables of the same name declaredinside one method to avoid confusion'

Page 44: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 44/68

44

 +!*e Casting+!*e Casting

Page 45: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 45/68

45

Type Castin

● "pe #asting

 – apping t"pe of an object to another 

● o be discussed

 – #asting data with primitive t"pes

 – #asting objects

Page 46: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 46/68

46

Castin Pri%itive Types

● #asting between primitive t"pes enables "ou to convertthe value of one data from one t"pe to another primitivet"pe'

● #ommonl" occurs between numeric t"pes'

● here is one primitive data t"pe that we cannot docasting though, and that is the boolean data t"pe'

● "pes of #asting:

 – !mplicit #asting

 – Explicit #asting

Page 47: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 47/68

47

I%plicit Castin

● uppose we want to store a value of int data t"pe to avariable of data t"pe double'

int numInt = 10;

double numDouble = numInt; //implicit cast

!n this example, since the destination variable0s data

t"pe (double holds a larger value than the value0s datat"pe (int, the data is implicitl" casted to the destinationvariable0s data t"pe double'

Page 48: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 48/68

48

I%plicit Castin

●  Another example:

int numInt1 = 1;

int numInt2 = 2;

//result is implicitly casted to type doubledouble numDouble = numInt1/numInt2; 

Page 49: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 49/68

49

E(plicit Castin

● hen we convert a data that has a large t"pe to asmaller t"pe, we must use an explicit cast'

● Explicit casts ta*e the following form:

(Type)value

where,

"pe - is the name of the t"pe "ou0re converting tovalue -is an expression that results in the value of the source t"pe

Page 50: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 50/68

50

E(plicit Castin E(a%ples

double valDouble = 10.12;

int valInt = (int)valDouble;

//convert valDouble to int type

double x = 10.2;int y = 2;

int result = (int)(x/y); //typecast result of operation to int

Page 51: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 51/68

51

Castin Objects

● !nstances of classes also can be cast into instances ofother classes, with one restriction: he source anddestination classes must be related b" inheritance> oneclass must be a subclass of the other' 

 – e0ll cover more about inheritance later'

● #asting objects is analogous to converting a primitivevalue to a larger t"pe, some objects might not need to

be cast explicitl"'

Page 52: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 52/68

52

Castin Objects

● o cast,

(classname)object where,

classname is the name of the destination class ?

object is a reference to the source object

Page 53: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 53/68

53

Castin Objects E(a%ple

● he following example casts an instance of the class7ice%resident to an instance of the class Emplo"ee>7ice%resident is a subclass of Emplo"ee with moreinformation, which here defines that the 7ice%resident

has executive washroom privileges'

Employee emp = new Employee();

 VicePresident veep = new VicePresident();

// no cast needed for upward use

emp = veep;

// must cast explicitly

veep = (VicePresident)emp;

Page 54: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 54/68

54

 Pri#itives $Pri#itives $Wra**er +!*esWra**er +!*es

Convertin Pri%itive types to

Page 55: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 55/68

55

Convertin Pri%itive types toObjects and vice versa

● $ne thing "ou can0t do under an" circumstance is castfrom an object to a primitive data t"pe, or vice versa'

●  As an alternative, the java'lang pac*age includes

classes that correspond to each primitive data t"pe:+loat, <oolean, <"te, and so on' e call them rapper  classes'

Page 56: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 56/68

56

Wrapper Classes

● ost of these classes have the same names as thedata t"pes, except that the class names begin with acapital letter

 – !nteger is a wrapper class of the primitive int

 – Double is a wrapper class of the primitive double

 – 6ong is a wrapper class of the primitive long

● @sing the classes that correspond to each primitivet"pe, "ou can create an object that holds the same

value'

Convertin Pri%itive types to

Page 57: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 57/68

57

ypObjects !Wrapper# and vice versa

● he following statement creates an instance of the !nteger classwith the integer value BC

"nteger data*ount ! new "nteger(+,01);

he following statement converts an !nteger object to its primitivedata t"pe int' he result is an int with value BC

int new*ount ! data*ount.int-alue();

●  A common translation "ou need in programs is converting a tringto a numeric t"pe, such as an int ($bject-primitive

String pennsylvania ! &000;

int penn ! "nteger.parse"nt(pennsylvania);

Page 58: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 58/68

58

 Co#*aring ObjectsCo#*aring Objects

C i Obj t

Page 59: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 59/68

59

Co%parin Objects

● !n our previous discussions, we learned aboutoperators for comparing valuesFe.ual, not e.ual, lessthan, and so on' ost of these operators wor* onl" onprimitive t"pes, not on objects'

● he exceptions to this rule are the operators fore.ualit": GG (e.ual and HG (not e.ual' hen applied toobjects, these operators don0t do what "ou might firstexpect' !nstead of chec*ing whether one object has thesame value as the other object, the" determine whetherboth sides of the operator refer to the same object'

Co%parin Objects

Page 60: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 60/68

60

Co%parin Objects

● Example:1 class EqualsTest2 {3 public static void main(String[] arguments) {4 String str1, str2;5 str1 = "Free the bound periodicals.";

6 str2 = str1;7 System.out.println("String1: " + str1);8 System.out.println("String2: " + str2);9 System.out.println("Same object? " + (str1 == str2));10 str2 = new String(str1);11 System.out.println("String1: " + str1);12 System.out.println("String2: " + str2);

13 System.out.println("Same object? " + (str1 == str2));14 System.out.println("Same value? " + str1.equals(str2));15 }16 }

C i Obj t

Page 61: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 61/68

61

Co%parin Objects

● his program0s output is as follows:

String1: Free the bound periodicals.

String2: Free the bound periodicals.

Same object? true

String1: Free the bound periodicals.

String2: Free the bound periodicals.

Same object? false

Same value? True

Co%parin Objects

Page 62: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 62/68

62

Co%parin Objects

● 3$E on trings: – ;iven the code:

String str1 ! “Hello”;String str ! “Hello”;

 – hese two references str and strI will point to the sameobject'

 – tring literals are optimi)ed in 1ava> if "ou create a stringusing a literal and then use another literal with the samecharacters, 1ava *nows enough to give "ou the first tring

object bac*'

 – <oth strings are the same objects> "ou have to go out of "ourwa" to create two separate objects'

Page 63: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 63/68

63

 getClass() #ethod $getClass() #ethod $instanceof O*erator instanceof O*erator 

,eter%inin the class of an object

Page 64: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 64/68

64

,eter%inin the class of an object

● ant to find out what an object0s class isJ 8ere0s the wa"to do it'

● uppose we have the following object:

SomeClassName key = new SomeClassName();

3ow, we0ll discuss two wa"s to *now the t"pe of theobject pointed to b" the variable key'

etClass!# %ethod

Page 65: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 65/68

65

etClass!# %ethod

● he get#lass( method returns a #lass object instance(where #lass is itself a class

● #lass class has a method called get3ame('

 – get3ame( returns a string representing the name of the class'

● +or Example,

String name = key.getClass().getName(); 

instanceof operator

Page 66: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 66/68

66

instanceof operator 

● he instanceof  has two operands: a reference to anobject on the left and a class name on the right'

● he expression returns true or false based on whether

the object is an instance of the named class or an" ofthat class0s subclasses'

● +or Example,

 boolean ex1 = "Texas" instanceof String; // trueObject pt = new Point(10, 10);

 boolean ex2 = pt instanceof String; // false

Page 67: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 67/68

67

 %u##ar!%u##ar!

$u%%ary

#l d $bj t

Page 68: Java Built in Classes

8/13/2019 Java Built in Classes

http://slidepdf.com/reader/full/java-built-in-classes 68/68

68

● #lasses and $bjects

 – !nstance variables

 – #lass 7ariables

● #lass !nstantiation

● ethods

 – !nstance methods

 – %assing 7ariables in ethods (%ass-b"-value, %ass-b"-reference

 – tatic methods

● cope of a variable

#asting (object, primitive t"pes● #onverting %rimitive "pes to $bjects and 7ice 7ersa

● #omparing $bjects

● Determining the #lass of an $bject