0% found this document useful (0 votes)
259 views

Java Built in Classes

This document discusses working with Java classes and provides an overview of object-oriented programming concepts like classes, objects, methods, variables, and type casting. It explains that classes are templates that define properties and behaviors, while objects are instances of classes that share behaviors but have unique property values. It also differentiates between instance and static methods/variables, and describes how to call methods and pass parameters by value and by reference. Finally, it covers variable scope and type casting between primitive types and objects.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
259 views

Java Built in Classes

This document discusses working with Java classes and provides an overview of object-oriented programming concepts like classes, objects, methods, variables, and type casting. It explains that classes are templates that define properties and behaviors, while objects are instances of classes that share behaviors but have unique property values. It also differentiates between instance and static methods/variables, and describes how to call methods and pass parameters by value and by reference. Finally, it covers variable scope and type casting between primitive types and objects.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Working with Java 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

Brief Introduction on OOP


3

Introduction to OOP

$bject-$riented programming or $$%


&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

Classes and Objects (Object Instances)


7

Classes and Objects

#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

(wo t"pes of class members:

+ields (properties, variables

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

,ethods (behavior

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 the ones of other object instances of a same class $bject instances of a same class share the same behavior (methods

Classes and Objects

(o differentiate between classes and objects, let us discuss an example:

10

Classes and Objects

#lasses provide the benefit of reusabilit"' -oftware programmers can use a class over and over again to create man" object instances'

11

Creation of Object Instances with new ke!word


12

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 the class -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 an instance without using new *e"word as shown above

13

Creation of Object Instance

(he new operator


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

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


15

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'

(he following are characteristics of methods:


!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

Why Use Methods?

,ethods contain behavior of a class (business logic


(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

Two Types of Methods

!nstance (non-static methods


-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

Callin Instance !non"static# Methods

(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

Callin Instance Methods

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

20

Callin Instance Methods

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

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);

22

Callin $tatic Methods

Examples of static methods, we0ve 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 ! "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 Passing (Pass&b!&value $ Pass&b!&reference)


24

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 ((ields) Pro*erties)


30

&ariables

Data identifiers Are used to refer to specific values that are generated in a program--values that "ou want to *eep around

31

Three Types of &ariables

6ocal (automatic variable


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

#lass (static 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 *

!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

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

6ocal (automatic variable

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

#lass (static 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

,apping t"pe of an object to another

(o be discussed

#asting data with primitive t"pes #asting objects

45

Castin Pri%itive Types

#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:

!mplicit #asting Explicit #asting


46

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;

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

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

E(plicit Castin E(a%ples


double int valDouble = 10.12; 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

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'

/e0ll cover more about inheritance later'

#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

(o cast, (classname)object where,


classname is the name of the destination class ? object is a reference to the source object

52

Castin Objects E(a%ple

(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

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


54

Convertin Pri%itive types to Objects and vice versa

$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

Convertin Pri%itive types to Objects !Wrapper# and vice versa

(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

(his program0s output is as follows:


String1: Free the bound String2: Free the bound Same object? true String1: Free the bound String2: Free the bound Same object? false Same value? True periodicals. periodicals. periodicals. periodicals.

61

Co%parin Objects

3$(E on -trings:

;iven the code: String str1 ! Hello; String str0 ! Hello;

(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

getClass() #ethod $ instanceof O*erator


63

,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 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( '

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

+or Example, String name = key.getClass().getName();

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

#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

68

You might also like