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

Lesson No

Uploaded by

Christian Joshua
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Lesson No

Uploaded by

Christian Joshua
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 19

Object-Oriented Programming

Lesson No. 6

OBJECTS AND CLASSES

What is the lesson all about?

In this section, we will introduce some basic concepts of object-oriented


programming. Later on, we will discuss the concept of classes and objects, and how to use
these classes and their members. Comparison, conversion and casting of objects will also be
covered. For now, we will focus on using classes that are already defined in the Java class
library, we will discuss later on how to create your own classes.

What do you expect from the lesson?

After the delivery 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/meth-
ods
 Explain what methods are and how to call and pass parameters to methods
 Identify the scope of a variable
 Cast primitive data types and objects
 Compare objects and determine the class of an objects

What are the contents of the lesson?

Object-Oriented programming or OOP revolves around the concept of


objects as the basic elements of your programs. When we compare this to the physical
world, we can find many objects around us, such as cars, lion, people and so on. These
objects are characterized by their properties (or attributes) and behaviors.

For example, a car object has the properties, type of transmission, manufacturer and color.
Its behaviors are turning, braking and accelerating. Similarly, we can define different
properties and behavior of a lion. Please refer to the table below for the examples.

juliomcervantes 97
Object-Oriented Programming

Object Properties Behavior


Car type of transmission turning
manufacturer braking
color accelerating
Lion Weight roaring
Color sleeping
hungry or not hungry hunting
tamed or wild
Table 1: Example of Real-life Objects

With these descriptions, the objects in the physical world can easily be modeled as software
objects using the properties as data and the behaviors as methods. These data and
methods could even be used in programming games or interactive software to simulate the
real-world objects! An example would be a car software object in a racing game or a lion
software object in an educational interactive software zoo for kids.

Classes and Objects

Difference Between Classes and Objects


In the software world, an object is a software component whose structure is similar to
objects in the real world. Each object is composed of a set of data (properties/attributes)
which are variables describing the essential characteristics of the object, and it also consists
of a set of methods (behavior) that describes how an object behaves. Thus, an object is a
software bundle of variables and related methods. The variables and methods in a Java
object are formally known as instance variables and instance methods to distinguish them
from class variables and class methods, which will be discussed later.

The class is the fundamental structure in object-oriented programming. It can be thought of


as a template, a prototype or a blueprint of an object. It consists of two types of members
which are called fields (properties or attributes) and methods. Fields specifiy the data types
defined by the class, while methods specify the operations. An object is an instance of the
class.

To differentiate between classes and objects, let us discuss an example. What we have here
is a Car Class which can be used to define several Car Objects. In the table shown below, Car
A and Car B are objects of the Car class. The class has fields plate number, color,
manufacturer, and current speed which are filled-up with corresponding values in objects
Car A and Car B. The Car has also some methods Accelerate, Turn and Brake.

Car Class Object Car A Object Car B


Plate Number ABC 111 XYZ 123
Variables
Instance

Color Blue Red


Manufacturer Mitsubishi Toyota
Current Speed 50 km/h 100 km/h

juliomcervantes 98
Object-Oriented Programming

Car Class Object Car A Object Car B


Instance Accelerate Method
Method Turn Method
s
Brake Method

Table 2: Example of Car class and its objects

When instantiated, each object gets a fresh set of state variables. However, the method
implementations are shared among objects of the same class.

Classes provide the benefit of reusability. Software programmers can use a class over and
over again to create many objects.

Encapsulation

Encapsulation is the method of hiding certain elements of the implementation of a certain


class. By placing a boundary around the properties and methods of our objects, we can
prevent our programs from having side effects wherein programs have their variables
changed in unexpected ways.

We can prevent access to our object's data by declaring them in a certain way such that we
can control access to them. We will learn more about how Java implements encapsulation as
we discuss more about classes.

Class Variables and Methods


In addition to the instance variables, it is also possible to define class variables, which are
variables that belong to the whole class. This means that it has the same value for all the
objects in the same class. They are also called static member variables.

To clearly describe class variables, let's go back to our Car class example. Suppose that our
Car class has one class variable called Count. If we change the value of Count to 2, all of the
objects of the Car class will have the value 2 for their Count variable.

Car Class Object Car A Object Car B


Plate Number ABC 111 XYZ 123
Variables
Instance

Color Blue Red


Manufacturer Mitsubishi Toyota
Current Speed 50 km/h 100 km/h
Variabl
Class

Count = 2
e

Accelerate Method
anc
Inst

Me
e

Turn Method

juliomcervantes 99
Object-Oriented Programming

Car Class Object Car A Object Car B


Brake Method

h
o
t Table 3: Car class' methods and variables

Class 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 String, we write the following code,

String str2 = new String(“Hello world!”);

or also equivalent to,

String str2 = "Hello";

Figure 1: Classs Instantiation

The new operator allocates a memory for that object and returns a reference of that
memory location to you. When you create an object, you actually invoke the class'
constructor. The constructor is a method where you place all the initializations, it has the
same name as the class.

Methods
What are Methods and Why Use Methods?
In the examples we discussed before, we only have one method, and that is the main()
method. In Java, we can define many methods which we can call from different methods.

A method is a separate piece of code that can be called by a main program or any other
method to perform some specific function.

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 function arguments.
 After the method has finished execution, it goes back to the method that called it.

Now, why do we need to create methods? Why don't we just place all the code inside one
big method? The heart of effective problem solving is in problem decomposition. We can do
this in Java by creating methods to solve a specific part of the problem. Taking a problem
and breaking it into small, manageable pieces is critical to writing large programs.

juliomcervantes 100
Object-Oriented Programming

Calling Instance Methods and Passing Variables

Now, to illustrate how to call methods, let's use the String class as an example. You can use
the Java API documentation to see all the available methods in the String class. Later on, we
will create our own methods, but for now, let us use what is available.

To call an instance method, we write the following,

nameOfObject.nameOfMethod( parameters );

Let's take two sample methods found in the class String,

Method declaration Definition


public char charAt(int index) Returns the character at the specified index.
An index ranges from 0 to length() - 1. The first
character of the sequence is at index 0, the next
at index 1, and so on, as for array indexing.
public boolean equalsIgnoreCase Compares this String to another String, ignoring
(String anotherString) case considerations. Two strings are considered
equal ignoring case if they are of the same length,
and corresponding characters in the two strings
are equal ignoring case.
Table 4: Sample Methods of class String

Using the methods,

String str1 = "Hello";


char x = str2.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( str1 );

Passing Variables in Methods

In our examples, we already tried passing variables to methods. However, we haven't


differentiated between the different types of variable passing in Java. There are two types of
passing data to methods, the first one is pass-by-value and then, pass-by-reference.

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 accidentally modify the original argument even if it
modifies the parameters during calculations.

For example,

juliomcervantes 101
Object-Oriented Programming

public class TestPassByValue


{
public static void main( String[] args ){
int i = 10;
//print the value of i
System.out.println( i );

//call method test


//and pass i to method test
Pass i as parameter
test( i ); which is copied to j

//print the value of i. i not changed


System.out.println( i );
}

public static void test( int j ){


//change value of parameter j
j = 33;
}
}

In the given example, we called the method test and passed the value of i as parameter. The
value of i is copied to the variable of the method j. Since j is the variable changed in the test
method, it will not affect the variable value if i in main since it is a different copy of the
variable.
By default, all primitive data types when passed to a method are pass-by-value.

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. However, 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.

For example,
class TestPassByReference
{
public static void main( String[] args ){
//create an array of integers
int []ages = {10, 11, 12};

//print array values


for( int i=0; i<ages.length; i++ ){
System.out.println( ages[i] );

//call test and pass reference to array


Pass ages as parameter test( ages );
which is copied to
variable arr //print array values again
for( int i=0; i<ages.length; i++ ){
System.out.println( ages[i] );

juliomcervantes 102
Object-Oriented Programming

}
}

public static void test( int[] arr ){


//change values of array
for( int i=0; i<arr.length; i++ ){
arr[i] = i + 50;
}
}
}

juliomcervantes 103
Object-Oriented Programming

Figure 2: Pass-by-reference example

Coding Guidelines:

A common misconception about pass-by-reference in Java is when creating a swap


method using Java references. Take note that Java manipulates objects 'by reference,'
but it passes object references to methods 'by value.'" As a result, you cannot write a
standard swap method to swap objects.

Calling Static Methods


Static methods are methods that can be invoked without instantiating a class (means
without invoking the new keyword). Static methods belongs to the class as a whole and not
to a certain instance (or object) of a class. Static methods are distinguished from instance
methods in a class definition by the keyword static.

To call a static method, just type,

Classname.staticMethodName(params);

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

juliomcervantes 104
Object-Oriented Programming

String hexEquivalent = Integer.toHexString( 10 );

Scope of a variable
In addition to a variable's data type and name, a variable has scope. The scope determines
where in the program the variable is accessible. The scope also determines the lifetime of a
variable or how long the variable can exist in memory. The scope is determined by where the
variable declaration is placed in the program.

To simplify things, just think of the scope as anything between the curly braces {...}. The
outer curly braces is called the outer blocks, and the inner curly braces is called inner blocks.

If you declare variables in the outer block, they are visible (i.e. usable) by the program lines
inside the inner blocks. However, if you declare variables in the inner block, you cannot
expect the outer block to see it.
A variable's scope is inside the block where it is declared, starting from the point where it is
declared, and in the inner blocks.

For example, given the following code snippet,

public class ScopeExample


{
public static void main( String[] args ){
int i = 0;
int j = 0;

//... some code here


A
B {
int k = 0;
int m = 0; D C
E int n = 0;
}
}

The code we have here represents five scopes indicated by the lines and the letters
representing the scope. Given the variables i,j,k,m and n, and the five scopes A,B,C,D and E,
we have the following scopes for each variable:
The scope of variable i is A.
The scope of variable j is B.
The scope of variable k is C.
The scope of variable m is D.
The scope of variable n is E.

Now, given the two methods main and test in our previous examples,

class TestPassByReference
{
public static void main( String[] args ){
//create an array of integers
int []ages = {10, 11, 12};
A
juliomcervantes 105
Object-Oriented Programming

//print array values


for( int i=0; i<ages.length; i++ ){
B System.out.println( ages[i] );
}

//call test and pass reference to array


test( ages );

//print array values again


for( int i=0; i<ages.length; i++ ){
C System.out.println( ages[i] );
}
}

public static void test( int[] arr ){


//change values of array
E for( int i=0; i<arr.length; i++ ){ D
arr[i] = i + 50;
}
}
}

In the main method, the scope of the variables are,

ages[] - scope A
i in B - scope B
i in C – scope C

In the test method, the scope ofthe variables are,

arr[] - scope D
i in E - scope E

When declaring variables, only one variable with a given identifier or name can be
declared in a scope. That means that if you have the following declaration,

{
int test = 10;
int test = 20;
}

your compiler will generate an error since you should have unique names for your
variables in one block. However, you can have two variables of the same name, if they
are not declared in the same block. For example,

int test = 0;
System.out.print( test );
//..some code here
{
int test = 20;
System.out.print( test );

juliomcervantes 106
Object-Oriented Programming

When the first System.out.print is invoke, it prints the value of the first test variable since it
is the variable seen at that scope. For the second System.out.print, the value 20 is printed
since it is the closest test variable seen at that scope.

Coding Guidelines:
Avoid having variables of the same name declared inside one method to avoid confusion.

Casting, Converting and Comparing Objects


In this section, we are going to learn how to do typecasting. Typecasting or casting is the
process of converting a data of a certain data type to another data type. We will also learn
how to convert primitive data types to objects and vice versa. And finally, we are going to
learn how to compare objects.

Casting Primitive Types


Casting between primitive types enables you to convert the value of one data from one type
to another primitive type. This commonly occurs between numeric types.

There is one primitive data type that we cannot do casting though, and that is the boolean
data type.

An example of typecasting is when you want to store an integer data to a variable of data
type double. For example,

int numInt = 10;


double numDouble = numInt; //implicit cast

In this example, since the destination variable (double) holds a larger value than what we
will place inside it, the data is implicitly casted to data type double.

Another example is when we want to typecast an int to a char value or vice versa. A
character can be used as an int because each character has a corresponding numeric code
that represents its position in the character set. If the variable i has the value 65, the cast
(char)i produces the character value 'A'. The numeric code associated with a capital A is 65,
according to the ASCII character set, and Java adopted this as part of its character support.
For example,

char valChar = 'A';


int valInt = valChar;
System.out.print( valInt ); //explicit cast: output 65

When we convert a data that has a large type to a smaller type, we must use an explicit cast.
Explicit casts take the following form:

(dataType)value

juliomcervantes 107
Object-Oriented Programming

where,
dataType, is the name of the data type you're converting to
value, is an expression that results in the value of the source type.

For example,

double valDouble = 10.12;


int valInt = (int)valDouble; //convert valDouble to int type

double x = 10.2;
inty = 2;

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

Casting Objects

Instances of classes also 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. We'll cover more about inheritance later.

Analogous to converting a primitive value to a larger type, some objects might not need to
be cast explicitly. In particular, because a subclass contains all the same information as its
superclass, you can use an instance of a subclass anywhere a superclass is expected.

For example, consider a method that takes two arguments, one of type Object and another
of type Window. You can pass an instance of any class for the Object argument because all
Java classes are subclasses of Object. For the Window argument, you can pass in its
subclasses, such as Dialog, FileDialog, and Frame. This is true anywhere in a program, not
just inside method calls. If you had a variable defined as class Window, you could assign
objects of that class or any of its subclasses to that variable without casting.

Figure 3: Sample Class Hierarchy

This is true in the reverse, and you can use a superclass when a subclass is expected. There is
a catch, however: Because subclasses contain more behavior than their superclasses,
there's a loss in precision involved. Those superclass objects might not have all the behavior
needed to act in place of a subclass object. For example, if you have an operation that calls

juliomcervantes 108
Object-Oriented Programming

methods in objects of the class Integer, using an object of class Number won't include many
methods specified in Integer. Errors occur if you try to call methods that the destination
object doesn't have.

To use superclass objects where subclass objects are expected, you must cast them
explicitly. You won't lose any information in the cast, but you gain all the methods and
variables that the subclass defines. To cast an object to another class, you use the same
operation as for primitive types:

To cast,

(classname)object

where,
classname, is the name of the destination class
object, is a reference to the source object.

Note: that casting creates a reference to the old object of the type classname; the old object
continues to exist as it did before.

Figure 4: Class Hierarchy for superclass Employee

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();
emp = veep; // no cast needed for upward use
veep = (VicePresident)emp; // must cast explicitlyCasting

Converting Primitive Types to Objects and Vice Versa

One thing you can't do under any circumstance is cast from an object to a primitive data
type, or vice versa. Primitive types and objects are very different things in Java, and you can't
automatically cast between the two or use them interchangeably.

juliomcervantes 109
Object-Oriented Programming

As an alternative, the java.lang package includes classes that correspond to each primitive
data type: Float, Boolean, Byte, and so on. Most of these classes have the same names as
the data types, except that the class names begin with a capital letter (Short instead of short,
Double instead of double, and the like). Also, two classes have names that differ from the
corresponding data type: Character is used for char variables and Integer for int variables.
(Called Wrapper Classes)

Java treats the data types and their class versions very differently, and a program won't
compile successfully if you use one when the other is expected.

Using the classes that correspond to each primitive type, you can create an object that holds
the same value.

Examples:

//The following statement creates an instance of the Integer


// class with the integer value 7801 (primitive -> Object)
Integer dataCount = new Integer(7801);

//The following statement converts an Integer object to


// its primitive data type int. The result is an int with
//value 7801
int newCount = dataCount.intValue();

// A common translation you need in programs


// is converting a String to a numeric type, such as an int
// Object->primitive
String pennsylvania = "65000";
int penn = Integer.parseInt(pennsylvania);

 CAUTION: The Void class represents nothing in Java, so there's no reason it would be
used when translating between primitive values and objects. It's a placeholder for
the void keyword, which is used in method definitions to indicate that the method
does not return a value.

Comparing Objects
In our previous discussions, we learned about operators for comparing values—equal, not
equal, less than, and so on. Most of these operators work only on primitive types, not on
objects. If you try to use other values as operands, the Java compiler produces errors.

The exceptions to this rule are the operators for equality: == (equal) and != (not equal).
When applied to objects, these operators don't do what you might first expect. Instead of
checking whether one object has the same value as the other object, they determine
whether both sides of the operator refer to the same object.

To compare instances of a class and have meaningful results, you must implement special
methods in your class and call those methods. A good example of this is the String class.

It is possible to have two different String objects that contain the same values. If you were to
employ the == operator to compare these objects, however, they would be considered

juliomcervantes 110
Object-Oriented Programming

unequal. Although their contents match, they are not the same object.

To see whether two String objects have matching values, a method of the class called
equals() is used. The method tests each character in the string and returns true if the two
strings have the same values.

The following code illustrates this,

class EqualsTest {
public static void main(String[] arguments) {
String str1, str2;
str1 = "Free the bound periodicals.";
str2 = str1;

System.out.println("String1: " + str1);


System.out.println("String2: " + str2);
System.out.println("Same object? " + (str1 == str2));

str2 = new String(str1);

System.out.println("String1: " + str1);


System.out.println("String2: " + str2);
System.out.println("Same object? " + (str1 == str2));
System.out.println("Same value? " + str1.equals(str2));
}
}

This program's output is as follows,

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

Now let's discuss the code.


String str1, str2;
str1 = "Free the bound periodicals.";

Figure 5: Both references point to the same object

juliomcervantes 111
Object-Oriented Programming

The first part of this program declares two variables (str1 and str2), assigns the literal "Free
the bound periodicals." to str1, and then assigns that value to str2. As you learned earlier,
str1 and str2 now point to the same object, and the equality test proves that.

str2 = new String(str1);

In the second part of this program, you create a new String object with the same value as
str1 and assign str2 to that new String object. Now you have two different string objects in
str1 and str2, both with the same value. Testing them to see whether they're the same
object by using the == operator returns the expected answer: false—they are not the same
object in memory. Testing them using the equals() method also returns the expected
answer: true—they have the same values.

Figure 6: References now point to different objects

NOTE: Why can't you just use another literal when you change str2, rather than using new?
String literals are optimized in Java; if you create a string using a literal and then use another
literal with the same characters, Java knows enough to give you the first String object back.
Both strings are the same objects; you have to go out of your way to create two separate
objects.

Determining the Class of an Object


Want to find out what an object's class is? Here's the way to do it for an object assigned to
the variable key:

1. 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.

For Example,

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

2. The 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.

For Example,

juliomcervantes 112
Object-Oriented Programming

boolean ex1 = "Texas" instanceof String; // true


Object pt = new Point(10, 10);
boolean ex2 = pt instanceof String; // false

Name: ________________________________________________________________________________________
Year & Section: ___________________________________ Date _____________________________________

SKILLS WARM-UP

Defining Terms. In your own word, define the following terms:


1. Class

2. Object

3. Instantiate

4. Instance Variable

5. Instance Method

6. Class Variables or static member variables

7. Constructor

8. Encapsulation

9. Typecasting

10. Polymorphism

juliomcervantes 113
Object-Oriented Programming

Name: ___________________________________________________________________
Year & Section: ______________________________ Date: _________________________

SKILLS WORKOUT

Java Scavenger Hunt

Pipoy is a newbie in the Java programming language. He just heard that there are
already ready-to-use APIs in Java that one could use in their programs, and he's eager to
try them out. The problem is, Pipoy does not have a copy of the Java Documentation,
and he also doesn't have an internet access, so there's no way for him to view the Java
APIs.

Your task is to help Pipoy look for the APIs (Application Programming Interface). You
should state the class where the method belongs, the method declaration and a sample
usage of the said method.

For example, if Pipoy wants to know the method that converts a String to integer, your
answer should be:

Class: Integer
Method Declaration: public static int parseInt( String value )
Sample Usage:
String strValue = "100";
int value = Integer.parseInt( strValue );

Make sure that the snippet of code you write in your sample usage compiles and outputs
the correct answer, so as not to confuse Pipoy. (Hint: All methods are in the
java.lang package). In cases where you can find more methods that can accomplish
the task, give only one.

Now let's start the search!

1. Look for a method that checks if a certain String ends with a certain suffix. For
example, if the given string is "Hello", the method should return true the suffix given
is "lo", and false if the given suffix is "alp".

2. Look for the method that determines the character representation for a specific digit in
the specified radix. For example, if the input digit is 15, and the radix is 16, the
method would return the character F, since F is the hexadecimal representation for the
number 15 (base 10).

juliomcervantes 114
Object-Oriented Programming

3. Look for the method that terminates the currently running Java Virtual Machine

4. Look for the method that gets the floor of a double value. For example, if I input a
3.13, the method should return the value 3.

5. Look for the method that determines if a certain character is a digit. For example, if I
input '3', it returns the value true.

juliomcervantes 115

You might also like