MSI 692: Special Topics - PowerPoint PPT Presentation

About This Presentation
Title:

MSI 692: Special Topics

Description:

Sanjay Goel, School of Business, University at Albany, SUNY. Object ... int[][] ragged = {{1,2}, {3,4,5}, {6}} // 3 rows each with different # of elements ... – PowerPoint PPT presentation

Number of Views:52
Avg rating:3.0/5.0
Slides: 35
Provided by: salvator5
Learn more at: https://www.albany.edu
Category:
Tags: msi | ragged | special | topics

less

Transcript and Presenter's Notes

Title: MSI 692: Special Topics


1
  • MSI 692 Special Topics
  • in Information Technology
  • Lecture 5 Objects
  • Sanjay Goel
  • University at Albany, SUNY
  • Fall 2004

2
Outline for the ClassArrays
  • 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

3
Object-Oriented Programming
4
Object-Oriented ProgrammingFeatures
  • There are four features of object-oriented
    programming
  • Abstraction
  • Encapsulation
  • Polymorphism
  • Inheritance

5
Object-Oriented ProgrammingAbstraction
  • 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.

6
Object-Oriented ProgrammingAbstraction Example
  • A hospital has a different way of characterizing
    the students compared to a school 

Hospital Mother Father Time of Birth Date of
Birth Tests run on the baby since birth Caesarean
vs. Vaginal
School Mother Father Date of Birth School
District Grades Level of education of parents
7
Object-Oriented ProgrammingEncapsulation
  • 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

8
Object-Oriented ProgrammingPrimitive 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.

9
Object-Oriented ProgrammingClass Types
  • Class types is defined as
  • class classname members of the class
  •  
  • class Fruit
  • int grams
  • int totalCalories ()
  • return grams 10

10
Object-Oriented ProgrammingDeclarations
  • 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

11
Recap
12
RecapArrays 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.

13
RecapDeclaration and Memory Allocation of Arrays
  • Declaring an Array
  • variableType arrayName
  • Memory allocation for an array
  • arrayName new variableTypearrayLength
  •  Declaring and Memory Allocation
  • variableType arrayName new
    variableTypearrayLength

14
RecapIndexing and Initialization of Arrays
  • Indexing of arrays
  • Arrays are indexed from 0 to length-1
  • Syntax
  • a0 ? First element of the array
  • alength-1 ? Last element of the array
  • ai-1 ? (i)th element of the array
  • Initialization of an array
  • While declaring
  • variableType arrayName val1, val2,
  • After declaring
  • ArrayNamei vali

15
RecapLength 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 lt 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

16
RecapMultidimensional 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 intexpr1expr2
  • 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

17
RecapPassing 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
  • The contents of the array are modified
  • The main program sees the changes to the array
  • show using stack
  • The array is assigned to another array in the
    method
  • No change happens in the calling method
  • ? show using stack

18
ArraysCopying 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 inta.length
  • for(int I 0 I lt a.length I)
  • theCopyI aI
  • 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

19
Objects and Classes
20
Objects and ClassesIntroduction
  • 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.

21
Objects and ClassesElements 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.

22
Objects and ClassesPackages 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.

23
Objects and ClassesSignature 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.

24
Objects and ClassesSignature 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

25
Objects and ClassesConstructors
  • 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

26
Objects and ClassesConstructors, 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.

27
Objects and ClassesScope
  • 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    

28
Objects and ClassesCalling 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

29
Objects and ClassesCalling 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)

30
Objects and ClassesCounter Class
Class Counter int counter void reset()
value 0 int get() return value void
click() value (value 1) 100 Class
CounterTest Public static void main()
Counter c1 new Counter() Counter c2
new Counter() c1.click() c2.click() c2.cl
ick() System.out.println(c1
c1.get() System.out.println(c2
c2.get() c2.reset() System.out.println(c2
c2.get()
  • Let us construct a counter
  • class What does it do?
  • increment
  • resets
  • gives you a count
  •  Let us create a counter class

31
Objects and ClassesClasses
  • 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

32
Objects and ClassesStandard 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.

33
Objects and ClassesString 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.

34
Objects and ClassesStandard Classes Palindrome
  • static boolean isPalindrome(String s)
  • int left 0
  • int right s.length() 1
  • while (left lt right)
  • if (s.charAt(left) ! s.charAt(right))
  • Return false
  • left
  • right--
  • return true
  •  

Let us create a class called person Class Person
int age String name String
sex   Passing
Write a Comment
User Comments (0)
About PowerShow.com