Java Built in Classes
Java Built in Classes
Objectives
At the end of the lesson, the student should be able to:
Explain object-oriented programming and some of its concepts Differentiate between classes and objects Differentiate between instance variables/methods and class(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
2
Introduction to OOP
&evolves around the concept of objects as the basic elements of "our programs' (hese objects are characteri)ed b" their properties and behaviors'
Introduction to OOP
Example of objects
objects in the ph"sical world can easil" be modeled as software objects using the properties as data and the behaviors as methods
5
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
#lass
can be thought of as a template, a protot"pe or a blueprint of an object is the fundamental structure in object-oriented programming
specif" the data t"pes defined b" the class specif" the operations
,ethods (behavior
$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 the ones of other object instances of a same class $bject instances of a same class share the same behavior (methods
10
#lasses provide the benefit of reusabilit"' -oftware programmers can use a class over and over again to create man" object instances'
11
(o create an object instance of a class, we use the new operator' +or example, if "ou want to create an instance of the class -tring, we write the following code,
String str2 = new String(Hello world!);
-tring class is a special (and onl" class "ou can create an instance without using new *e"word as shown above
13
allocates a memor" for that object and returns a reference of that memor" location to "ou' /hen "ou create an object, "ou actuall" invo*e the class0 constructor'
(he constructor
is a method where "ou place all the initiali)ations, it has the same name as the class'
14
Methods
,ethod
is a separate piece of code that can be called b" a main program or an" other method to perform some specific function'
!t can return one or no values !t ma" accept as man" parameters it needs or no parameter at all' %arameters are also called arguments' After the method has finished execution, it goes bac* to the method that called it'
16
(he heart of effective problem solving is in problem decomposition' /e can do this in 1ava b" creating methods to solve a specific part of the problem' (a*ing a problem and brea*ing it into small, manageable pieces is critical to writing large programs'
17
-hould be called after object instance is created ,ore common than static methods -hould be called in the form of 2#lass3ame4'2method3ame4
-tatic methods
18
(o illustrate how to call methods, let0s use the String class as an example' 5ou can use the 1ava A%! documentation to see all the available methods in the -tring class' 6ater on, we will create our own methods, but for now, let us use what is available' (o call an instance method, we write the following,
nameOfObject.nameOfMethod( parameters );
Example
String strInstance1 = new String("I am object instance of a String class"); char x = strInstance1.charAt(2);
19
20
Example
String str1 = "Hello"; char x = str1.charAt(0); //will return the character H //and store it to variable x str2 = "hello";
String
//this will return a boolean value true boolean result = str1.equalsIgnoreCase( str2 );
21
-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'
22
//prints data to screen System.out.println(Hello world); //converts the String 10 to an integer int 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 );
23
Para%eter Passin
%ass-b"-7alue
when a pass-b"-value occurs, the method ma*es a cop" of the value of the variable passed to the method' (he method cannot 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'
25
Pass"by"&alue
26
Para%eter Passin
%ass-b"-&eference
/hen a pass-b"-reference occurs, the reference to an object is passed to the calling method' (his means that, the method ma*es a cop" of the reference of the variable passed to the method' 8owever, unli*e in pass-b"-value, the method can modif" the actual object that the reference is pointing to, since, although different references are used in the methods, the location of the data the" are pointing to is the same'
27
Pass"by"'eference
28
Pass"by"'eference
29
&ariables
Data identifiers Are used to refer to specific values that are generated in a program--values that "ou want to *eep around
31
declared within a method bod" visible onl" within a method bod" maintained in a stac* declared inside a class bod" but outside of an" method bodies per each object instance cannot be referenced from static context declared inside a class bod" but outside of an" method bodies prepended with the static modifier per each class shared b" all object instances
32
!nstance variable
%co*e of a 'ariable
33
$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 variable can exist in memor"' (he scope is determined b" where the variable declaration is placed in the program'
(o simplif" things, just thin* of the scope as an"thing between the curl" braces 9''':' (he outer curl" braces are called the outer bloc*s, and the inner curl" braces are called inner bloc*s'
34
$cope of a &ariable
A variable0s scope is
inside the bloc* where it is declared, starting from the point where it is declared
35
E(a%ple )
36
E(a%ple )
(he code we have in the previous slide represents five scopes indicated b" the lines and the letters representing the scope' ;iven the variables i,j,*,m and n, and the five scopes A,<,#,D and E, we have the following scopes for each variable:
(he scope of variable i is A' (he scope of variable j is <' (he scope of variable * is #' (he scope of variable m is D' (he scope of variable n is E'
37
E(a%ple *
38
E(a%ple *
39
$cope of a &ariable
/hen declaring variables, onl" one variable with a given 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 should have uni.ue names for "our variables in one bloc*'
40
$cope of a &ariable
8owever, "ou can have two variables of the same name, if the" are not declared in the same bloc*' +or example,
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
41
$cope of &ariables
onl" valid from the line the" are declared on until the closing curl" brace of the method or code bloc* within which the" are declared most limited scope valid as long as the object instance is alive in scope from the point the class is loaded into the 17, until the the class is unloaded' #lass are loaded into the 17, the first time the class is referenced
42
!nstance variable
Codin +uidelines
Avoid having variables of the same name declared inside one method to avoid confusion'
43
+!*e Casting
44
Type Castin
("pe #asting
(o be discussed
45
#asting between primitive t"pes enables "ou to convert the value of one data from one t"pe to another primitive t"pe' #ommonl" occurs between numeric t"pes' (here is one primitive data t"pe that we cannot do casting though, and that is the boolean data t"pe' ("pes of #asting:
I%plicit Castin
-uppose we want to store a value of int data t"pe to a variable of data t"pe double'
int double numInt = 10; numDouble = numInt; //implicit cast
!n this example, since the destination variable0s data t"pe (double holds a larger value than the value0s data t"pe (int , the data is implicitl" casted to the destination variable0s data t"pe double'
47
I%plicit Castin
Another example:
int int numInt1 = 1; numInt2 = 2;
48
E(plicit Castin
/hen we convert a data that has a large t"pe to a smaller t"pe, we must use an explicit cast' Explicit casts ta*e the following form: (Type)value where,
("pe value - is the name of the t"pe "ou0re converting to -is an expression that results in the value of the source t"pe
49
//convert valDouble to int type double x = 10.2; int y = 2; int result = (int)(x/y); //typecast result of operation to int
50
Castin Objects
!nstances of classes also can be cast into instances of other classes, with one restriction: (he source and destination classes must be related b" inheritance> one class must be a subclass of the other'
#asting objects is analogous to converting a primitive value to a larger t"pe, some objects might not need to be cast explicitl"'
51
Castin Objects
52
(he following example casts an instance of the class 7ice%resident to an instance of the class Emplo"ee> 7ice%resident is a subclass of Emplo"ee with more information, 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;
53
$ne thing "ou can0t do under an" circumstance is cast from 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'
55
Wrapper Classes
,ost of these classes have the same names as the data t"pes, except that the class names begin with a capital 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 primitive t"pe, "ou can create an object that holds the same value'
56
(he following statement creates an instance of the !nteger class with the integer value ABCD
"nteger data*ount ! new "nteger(+,01);
(he following statement converts an !nteger object to its primitive data t"pe int' (he result is an int with value ABCD
int new*ount ! data*ount.int-alue();
A common translation "ou need in programs is converting a -tring to a numeric t"pe, such as an int ($bject-Eprimitive
String pennsylvania ! .&/000.; int penn ! "nteger.parse"nt(pennsylvania);
57
Co#*aring Objects
58
Co%parin Objects
!n our previous discussions, we learned about operators for comparing valuesFe.ual, not e.ual, less than, and so on' ,ost of these operators wor* onl" on primitive t"pes, not on objects' (he exceptions to this rule are the operators for e.ualit": GG (e.ual and HG (not e.ual ' /hen applied to objects, these operators don0t do what "ou might first expect' !nstead of chec*ing whether one object has the same value as the other object, the" determine whether both sides of the operator refer to the same object'
59
Co%parin Objects
Example:
1 class EqualsTest 2 { 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 }
60
Co%parin Objects
61
Co%parin Objects
3$(E on -trings:
(hese two references strD and strI will point to the same object' -tring literals are optimi)ed in 1ava> if "ou create a string using a literal and then use another literal with the same characters, 1ava *nows enough to give "ou the first -tring object bac*' <oth strings are the same objects> "ou have to go out of "our wa" to create two separate objects'
62
/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 the object pointed to b" the variable key'
64
etClass!# %ethod
(he get#lass( method returns a #lass object instance (where #lass is itself a class #lass class has a method called get3ame( '
65
instanceof operator
(he instanceof has two operands: a reference to an object 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" of that class0s subclasses' +or Example,
boolean ex1 = "Texas" instanceof String; // true Object pt = new Point(10, 10); boolean ex2 = pt instanceof String; // false
66
%u##ar!
67
$u%%ary
-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
68