Working With Java Classes
Working With Java Classes
Classes
1
Objectives
At the end of the lesson, the student should be able to:
4
Introduction to OOP
● Example of objects
● Encapsulation
– The scheme of hiding implementation details of a class.
– The caller of the class does not need to know the
implementation details of a class
– The implementation can change without affecting the caller of
the class
6
Classes and
Objects (Object
Instances)
7
Classes and Objects
● Class
– can be thought of as a template, a prototype or a blueprint of an
object
– is the fundamental structure in object-oriented programming
8
Classes and Objects
● Object
– An object is an instance of a class - we will call it object instance
– The property values of an object instance is different from the
ones of other object instances of a same class
– Object instances of a same class share the same behavior
(methods)
9
Classes and Objects
● To differentiate between classes and objects, let us
discuss an example:
10
Classes and Objects
● Classes provide the benefit of reusability.
11
Creation of Object
Instances with
“new” keyword
12
Creation of Object Instance
● To create an object 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
String str2 = "Hello world!";
● String class is a special (and only) class you can create an
instance without using new keyword as shown above
13
Creation of Object Instance
● 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.
14
Methods
(Instance methods &
Static methods)
15
Methods
● Method
– is a separate piece of code that can be called by a main
program or any other method to perform some specific
function.
16
Why Use Methods?
● Methods contain behavior of a class (business logic)
– 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.
17
Two Types of Methods
● Instance (non-static) methods
– Should be called after object instance is created
– More common than static methods
● Static methods
– Should be called in the form of [ClassName].[methodName]
18
Calling Instance (non-static)
Methods
● 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 );
● Example
String strInstance1 = new String("I am object
instance of a String class");
char x = strInstance1.charAt(2);
19
Calling Instance Methods
● Let's take two sample methods found in the String class
20
Calling Instance Methods
● Example
21
Calling Static Methods
● Static methods
– methods that can be invoked without instantiating a class
(means without invoking the new keyword).
– Static methods belong 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.
Classname.staticMethodName(params);
22
Calling Static Methods
● Examples of static methods, we've used so far in our
examples are,
23
Parameter Passing
(Pass-by-value &
Pass-by-reference)
24
Parameter Passing
● 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.
– all primitive data types when passed to a method are pass-by-
value.
25
Pass-by-Value
26
Parameter Passing
● 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.
27
Pass-by-Reference
28
Pass-by-Reference
29
Variables (Fields,
Properties)
30
Variables
● Data identifiers
● Are used to refer to specific values that are generated
in a program--values that you want to keep around
31
Three Types of Variables
● Local (automatic) variable
– declared within a method body
– visible only within a method body
– maintained in a stack
● Instance variable
– declared inside a class body but outside of any method bodies
– per each object instance
– cannot be referenced from static context
● Class (static) variable
– declared inside a class body but outside of any method bodies
– prepended with the static modifier
– per each class
– shared by all object instances 32
Scope of a Variable
33
Scope of a Variable
● The scope
– determines where in the program the variable is accessible.
– 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.
34
Scope of a Variable
● A variable's scope is
– inside the block where it is declared, starting from the point
where it is declared
35
Example 1
36
Example 1
● The code we have in the previous slide 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.
37
Example 2
38
Example 2
● In the main method, the scopes of the variables are,
– ages[] - scope A
– i in B - scope B
– i in C – scope C
39
Scope of a Variable
{
int test = 10;
int test = 20;
}
40
Scope of a Variable
● However, you can have two variables of the same
name, if they are not declared in the same block. For
example,
public class Main {
static int test = 0;
public static void main(String[] args) {
System.out.println(test); // prints 0
// test variable is defined in a new block
{
int test = 20;
System.out.println(test);// prints 20
}
System.out.println(test); // prints 0
}
} 41
Scope of Variables
● Local (automatic) variable
– only valid from the line they are declared on until the closing
curly brace of the method or code block within which they are
declared
– most limited scope
● Instance variable
– valid as long as the object instance is alive
● Class (static) variable
– in scope from the point the class is loaded into the JVM until
the the class is unloaded. Class are loaded into the JVM the
first time the class is referenced
42
Coding Guidelines
43
Type Casting
44
Type Casting
● Type Casting
– Mapping type of an object to another
● To be discussed
– Casting data with primitive types
– Casting objects
45
Casting Primitive Types
● Casting between primitive types enables you to convert
the value of one data from one type to another primitive
type.
● Types of Casting:
– Implicit Casting
– Explicit Casting
46
Implicit Casting
47
Implicit Casting
● Another example:
int numInt1 = 1;
int numInt2 = 2;
48
Explicit Casting
● When we convert a data that has a large type to a
smaller type, we must use an explicit cast.
(Type)value
where,
49
Explicit Casting Examples
50
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.
51
Casting Objects
● To cast,
(classname)object
where,
52
Casting Objects Example
● 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();
53
Primitives &
Wrapper Types
54
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
until JDK 5
– As an alternative, the java.lang package includes classes that
correspond to each primitive data type: Float, Boolean, Byte,
and so on. We call them Wrapper classes.
● In JDK 5, the autoboxing and unboxing automatically
handles the conversion
55
Wrapper Classes
● Most of these classes have the same names as the
data types, except that the class names begin with a
capital letter
– Integer is a wrapper class of the primitive int
– Double is a wrapper class of the primitive double
– Long is a wrapper class of the primitive long
● Using the classes that correspond to each primitive
type, you can create an object that holds the same
value.
56
Converting Primitive types to
Objects (Wrapper) and vice versa
● The following statement creates an instance of the Integer class
with the integer value 7801
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);
57
Comparing Objects
58
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.
● 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.
59
Comparing 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
Comparing Objects
● This program's 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
61
Comparing Objects
● NOTE on Strings:
– Given the code:
62
getClass() method &
instanceof Operator
63
Determining the class of an object
● Want to find out what an object's class is? Here's the way
to do it.
64
getClass() method
● The getClass() method returns a Class object instance
(where Class is itself a class)
● Class class has a method called getName().
● For Example,
65
instanceof operator
● The instanceof has two operands: a reference to an
object on the left and a class name on the right.
● For Example,
boolean ex1 = "Texas" instanceof String; // true
Object pt = new Point(10, 10);
boolean ex2 = pt instanceof String; // false
66
Summary
67
Summary
● Classes and Objects
– Instance variables
– Class Variables
● Class Instantiation
● Methods
– Instance methods
– Passing Variables in Methods (Pass-by-value, Pass-by-
reference)
– Static methods
● Scope of a variable
● Casting (object, primitive types)
● Converting Primitive Types to Objects and Vice Versa
● Comparing Objects
● Determining the Class of an Object
68