lecture4 - University at Albany

Download Report

Transcript lecture4 - University at Albany

MSI 692: Special Topics
in Information Technology
Lecture 5: Objects
Sanjay Goel
University at Albany, SUNY
Fall 2004
Sanjay Goel, School of Business, University at Albany, SUNY
1
Outline for the Class
Arrays
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Recap
Objects
Elements of a Simple Class
Packages and Data Hiding
Signatures of Method
Signatures of Data Fields
Constructors
Constructors, Methods, and Objects
Arrays of Objects
Scope
Calling a method in the same class
Calling a method in a different class
Counter class
String
Palindrome
Sanjay Goel, School of Business, University at Albany, SUNY
2
Object-Oriented Programming
Sanjay Goel, School of Business, University at Albany, SUNY
3
Object-Oriented Programming
Features
• There are four features of object-oriented
programming
–
–
–
–
Abstraction
Encapsulation
Polymorphism
Inheritance
Sanjay Goel, School of Business, University at Albany, SUNY
4
Object-Oriented Programming
Abstraction
• Abstraction is the process of refining away the
unimportant details of an object so that only the
appropriate characteristics that define it remain.
• These together with the operations on the data define
an abstract type.
• The same object can be abstracted differently depending
on the context.
Sanjay Goel, School of Business, University at Albany, SUNY
5
Object-Oriented Programming
Abstraction Example
• A hospital has a different way of characterizing the
students compared to a school
Hospital
School
Mother
Father
Time of Birth
Date of Birth
Tests run on the baby since birth
Caesarean vs. Vaginal
Mother
Father
Date of Birth
School District
Grades
Level of education of parents
Sanjay Goel, School of Business, University at Albany, SUNY
6
Object-Oriented Programming
Encapsulation
• Encapsulation is the process of bundling together types
and the functions that operate on those types and
restricting access to the internal representation on the
user-defined types.
• Operations on built in types are + - * /
• Operations on user-defined types are expressed as
functions
Sanjay Goel, School of Business, University at Albany, SUNY
7
Object-Oriented Programming
Primitive Types
• Object oriented programming is all about support for
class types and operations on them. The data types and
operations bundled together with restrictions on how
they are used are called a class.
• For primitive types the definition and the operations are
already known
• Primitive Types – There are eight built in types in java
…i.e.
• These are called primitive types because they are not
made up of any other types in contrast to class types or
array types.
Sanjay Goel, School of Business, University at Albany, SUNY
8
Object-Oriented Programming
Class Types
• Class types is defined as:
class classname {members of the class}
class Fruit {
int grams;
int totalCalories () {
return grams * 10;
}
}
Sanjay Goel, School of Business, University at Albany, SUNY
9
Object-Oriented Programming
Declarations
• Variables and objects are instantiated by declaring
them
• If a primitive is declared we get a variable
– When a primitive is declared a place in memory is
created for the variable
• If a user defined type is declared we get an
object
– We only get a reference to the object. Only when
initialized we will get a real object
Sanjay Goel, School of Business, University at Albany, SUNY
10
Recap
Sanjay Goel, School of Business, University at Albany, SUNY
11
Recap
Arrays and Variables
• Array is a container that holds a related group of values of the
same type.
– Arrays have a fixed length
– Elements in the array are numbered from 0 to n-1
– Position of an element in the array is called the index of the array
• Storage of Variables
• Primitive Variables
– These point to actual data. Which means that if you read the value at the
address to which the variable points you get the data.
• Reference Variables
– These are variables that point to a reference to the data rather than the
data itself.
Sanjay Goel, School of Business, University at Albany, SUNY
12
Recap
Declaration and Memory Allocation of Arrays
• Declaring an Array
variableType [] arrayName
• Memory allocation for an array
arrayName = new variableType[arrayLength]
• Declaring and Memory Allocation
variableType [] arrayName = new
variableType[arrayLength]
Sanjay Goel, School of Business, University at Albany, SUNY
13
Recap
Indexing and Initialization of Arrays
• Indexing of arrays
– Arrays are indexed from 0 to length-1
– Syntax:
a[0]  First element of the array
a[length-1]  Last element of the array
a[i-1]  (i)th element of the array
• Initialization of an array
– While declaring
variableType[] arrayName = {val1, val2, …}
– After declaring
ArrayName[i] = vali
Sanjay Goel, School of Business, University at Albany, SUNY
14
Recap
Length and Types of Arrays
• Length of an array
– Length of the array is stored in a variable called length and can be accessed as:
arrayName.length
for (int i = 0; i < a.length. i++) {
}
• Note: If you index past the end of the array you get an
IndexOutOfBoundsException error.
• Types and Arrays
• Primitive Types
– double [] d is an array of doubles
– char [] c is an array of characters
• Non-Primitive Types
– String[] args is an array of Strings
– Point[] points is an array of points
Sanjay Goel, School of Business, University at Albany, SUNY
15
Recap
Multidimensional Array
• Just like single dimensional arrays we have multi-dimensional
arrays
int[] a1;
Row
int[][] a2;
Matrix
int[][][] a3;
3D Grid
• Declaring 2D arrays
int[][] a2 = new int[expr1][expr2];
• Initializing 2D arrays
int[][] a = {{1,2},{3,4},{5,6}};
// 3x2
int[][] b = {{1,2,3}, {4,5,6}};
// 2x3
int[][] c = {{1,2,3,4,5,6}};
// 1x3
int[][] ragged = {{1,2}, {3,4,5}, {6}} // 3 rows each with different # of elements
Sanjay Goel, School of Business, University at Albany, SUNY
16
Recap
Passing arrays to methods
•
Java passes parameters by value.
•
Arrays are reference types i.e. they store the address of the array
location
•
So when we pass arrays as arguments a copy of the reference
value (address) is passed to the method.
•
Two Scenarios
1.
The contents of the array are modified
a.
The main program sees the changes to the array
 show using stack
2.
The array is assigned to another array in the method
a.
No change happens in the calling method
 show using stack
Sanjay Goel, School of Business, University at Albany, SUNY
17
Arrays
Copying Arrays
• You need to copy arrays element by element rather than just assigning one
array to another. By just assigning one array name to another you are just
copying pointers without copying the array.
• If you want to create a new array from an old array you need to create a new
array and assign all the values from the old array to the new array, e.g.
static int[] duplicate(int[] a) {
int[] theCopy = new int[a.length];
for(int I = 0; I < a.length; I++) {
theCopy[I] = a[I];
}
return theCopy;
}
a1 = duplicate(a2)
• Cloning: For one-dim arrays java provides a cloning mechanism
– i.e. a1 = (int[])a2.clone(); // built-in array copy
Sanjay Goel, School of Business, University at Albany, SUNY
18
Objects and Classes
Sanjay Goel, School of Business, University at Albany, SUNY
19
Objects and Classes
Introduction
• Objects are used to represent data values.
• They are called objects since they are used to model
objects in the real world. In Java objects are created by
creating classes.
Sanjay Goel, School of Business, University at Albany, SUNY
20
Objects and Classes
Elements of a Simple Class
•
A class describes data values that make up an object from the
described class and the operations that can be applied to the class.
– Instance Variables store data values
– Instance methods are methods that manipulate the data
(Implicit first argument is the object itself in these methods)
– Instance methods are used for object oriented programming
– Class or Static Methods are methods that do not operate on specific
instance of a class, i.e. they do not need to use instance methods or
variables
– These methods are used for structured programming, i.e. breaking down
logic into simpler pieces
– Class or Static variables are also independent of the class objects. There is
only one instance of a class variable no matter how many objects from the
class you create.
Sanjay Goel, School of Business, University at Albany, SUNY
21
Objects and Classes
Packages and Data Hiding
• Packages
– Classes in java are organized in groups called packages.
– If you place a bunch of files in the same directory they belong
to the same package.
• Data Hiding
– With appropriate syntax methods of one class can access
instance methods, class methods, instance variables and class
variables of another class.
Sanjay Goel, School of Business, University at Albany, SUNY
22
Objects and Classes
Signature of Method
Visibility Usage-Modifiers Return-Type Identifier (ParameterList) block
• Visibility
– Public: visible everywhere (as long as the class is public)
– Protected: like default (visible in subclasses in other packages)
– (blank): visible in the package (default)
– Private: visible in this class only
– Note: In main() method you can not leave visibility blank
• Usage-Modifiers
– Final: Can not be overridden
– Static: one per class (not each object instance)
– (Attached to class not object)
– abstract: must be overridden
– native: not written in Java. The body will be written in another language
– Synchronized: only one thread may execute in the method at a time.
Sanjay Goel, School of Business, University at Albany, SUNY
23
Objects and Classes
Signature of Data Fields
• Visibility
– Public: visible everywhere (as long as the class is public)
– Protected: like default (visible in subclasses in other packages)
– (blank): visible in the package (default)
– Private: visible in this class only
•
Usage-Modifiers
– Final: Can not be overridden
– Static: one per class (not each object instance)
(Attached to class not object)
– transient: used in object serialization
– volatile: can be written to by multiple threads, so runtime has to be careful
to get the latest value at all the time
Sanjay Goel, School of Business, University at Albany, SUNY
24
Objects and Classes
Constructors
•
•
•
•
•
•
•
All classes have one or more constructors.
These methods are called when you instantiate the
object.
The purpose of the constructor is to create the object
and initialize the values
You need multiple constructors since you want to
initialize the data with different sets of data
It is a method with two special characteristics:
It has no return type
It has the same name as the name of the class
Sanjay Goel, School of Business, University at Albany, SUNY
25
Objects and Classes
Constructors, Methods, & Objects
•
Default Constructor:
–
A no value constructor or the default constructor is provided by the
compiler by default and does not need to be defined by user
–
If any constructor is defined then no value constructor is not provided
by the compiler
•
Access Methods
–
•
Some times methods are defined to allow access to the private fields of
the class
Passing Objects
–
Objects are passed by reference
–
i.e. pointers to the object are passed
•
Arrays of Objects
–
Same as any arrays that we have done before.
Sanjay Goel, School of Business, University at Albany, SUNY
26
Objects and Classes
Scope
•
•
•
•
•
•
•
•
•
•
Scope of a local variable starts from the point of declaration and continues
until the end of the block.
Class variables have a scope over the range of statements they are visible
Scope of both class variables and instance variables is the entire class
Local variables must be declared prior to their use
Instance and class variables can be declared at the end of the class and still
be referenced in the methods defined earlier
When the local variable and a class variable have the same name, the local
variable takes precedence
To access the class variable the keyword this can be used to access the class
variable
Local variables can not be accessed outside the method in which it is
defined.
Class Constants (Final)
Arrays of Objects
Sanjay Goel, School of Business, University at Albany, SUNY
27
Objects and Classes
Calling a method in the same class
•
One class method from another class method, or
instance method from another instance method, or
class method from an instance method
–
Use the name followed by argument list.
–
Note: The implicit first argument of an instance method is the object
to which the operation applies. So it just uses that object for the
operation
•
One instance method from a class method
–
Needs to explicitly specify the object to which it applies
Sanjay Goel, School of Business, University at Albany, SUNY
28
Objects and Classes
Calling a method in a different class
•
Calling instance methods
–
To call non static or instance methods in a different class the syntax is
objectname followed by period followed by the method.
Str1.toCharArray();
Steps:
•
•
Create an object
•
Invoke method on the object
Calling class methods
–
Within the same class just use name followed by arguments
–
In a different class precede the name of the method with the name of
the class
–
e.g. Math.sqrt(x), Math.pow(a, b)
Sanjay Goel, School of Business, University at Albany, SUNY
29
Objects and Classes
Counter Class
•
Class Counter {
Let us construct a counter
int counter;
void reset() { value = 0;}
int get() {return value;}
class – What does it do?
–
–
–
•
increment
void click() { value = (value + 1) %100;}
}
Class CounterTest {
Public static void main() {
resets
Counter c1 = new Counter();
Counter c2 = new Counter();
gives you a count
c1.click();
Let us create a counter class
c2.click();
c2.click();
System.out.println(“c1 = ” + c1.get();}
System.out.println(“c2 = ” + c2.get();}
c2.reset();
System.out.println(“c2 = “ + c2.get();}
}
}
Sanjay Goel, School of Business, University at Albany, SUNY
30
Objects and Classes
Classes
•
So far we have learned how to create classes
•
There are two kinds of classes
–
Standard Classes: Classes defined in the standard java
package. We need standard classes for classes which are
most commonly used.
–
User Defined Classes: Classes defined for individual
applications
Sanjay Goel, School of Business, University at Albany, SUNY
31
Objects and Classes
Standard Classes: String
•
String class represents character strings
•
All string literals in Java programs are implemented as instances
of this class, e.g. “abc”
•
String class includes methods for examining individual
characters of the sequence, for comparing strings, for searching
strings, for extracting substrings, and for creating a copy of a
string with upper or lower case translation.
Sanjay Goel, School of Business, University at Albany, SUNY
32
Objects and Classes
String Methods
•
String class has following methods
–
boolean equals(Object anObject) Compares this string with another
–
int length() Gets length of string
–
char CharAt(int index) Returns char at index pos. in string
–
int compareTo(String str) Returns an integer based on lexigographic order
–
int indexOf(in ch) Gets position of character in string (-1 if not present)
–
int indexOf(String str) gets position of first letter of str in the string
–
String concat(String str) concats two strings and returns
–
String toLowerCase() converts to lower case
–
String toUpperCase() converts to upper case
–
Char[] toCharArray() returns character array
–
Static String valueof(type prim) converts primitive to string.
Sanjay Goel, School of Business, University at Albany, SUNY
33
Objects and Classes
Standard Classes: Palindrome
static boolean isPalindrome(String s) {
int left = 0;
Let us create a class called person:
Class Person {
int right = s.length() – 1;
int age;
while (left < right) {
String name
if (s.charAt(left) != s.charAt(right))
Return false;
String sex
}
left++;
right--;
Passing
}
return true;
}
Sanjay Goel, School of Business, University at Albany, SUNY
34