Lesson No
Lesson No
Lesson No. 6
After the delivery of the lesson, the student should be able to:
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
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.
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.
juliomcervantes 98
Object-Oriented Programming
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
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.
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.
Count = 2
e
Accelerate Method
anc
Inst
Me
e
Turn Method
juliomcervantes 99
Object-Oriented Programming
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,
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.
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
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.
nameOfObject.nameOfMethod( parameters );
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
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};
juliomcervantes 102
Object-Oriented Programming
}
}
juliomcervantes 103
Object-Oriented Programming
Coding Guidelines:
Classname.staticMethodName(params);
juliomcervantes 104
Object-Oriented Programming
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.
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
ages[] - scope A
i in B - scope B
i in C – scope C
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.
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,
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,
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 x = 10.2;
inty = 2;
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.
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.
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,
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:
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.
class EqualsTest {
public static void main(String[] arguments) {
String str1, str2;
str1 = "Free the bound periodicals.";
str2 = str1;
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
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.
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.
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.
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,
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
Name: ________________________________________________________________________________________
Year & Section: ___________________________________ Date _____________________________________
SKILLS WARM-UP
2. Object
3. Instantiate
4. Instance Variable
5. Instance Method
7. Constructor
8. Encapsulation
9. Typecasting
10. Polymorphism
juliomcervantes 113
Object-Oriented Programming
Name: ___________________________________________________________________
Year & Section: ______________________________ Date: _________________________
SKILLS WORKOUT
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.
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