Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 5: Objects Sanjay Goel University.

Slides:



Advertisements
Similar presentations
Chapter 21 Implementing lists: array implementation.
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Chapter 7: User-Defined Functions II
Lecture 2: Object Oriented Programming I
ITEC200 – Week03 Inheritance and Class Hierarchies.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Chapter 12: Adding Functionality to Your Classes.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
From C++ to Java A whirlwind tour of Java for C++ programmers.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Learners Support Publications Classes and Objects.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 10 Abstraction - The concept of abstraction is fundamental in programming - Nearly all programming.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
Introduction To Objects Oriented Programming Instructor: Mohammed Faisal.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
Java Programming Language Lecture27- An Introduction.
Lecture 3: Introduction to Object and Classes Michael Hsu CSULA.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Modern Programming Tools And Techniques-I
Topic: Classes and Objects
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
Corresponds with Chapter 7
The Building Blocks Classes: Java class library, over 1,800 classes:
Classes and Objects.
Java Programming Language
Java Basics Data Types in Java.
Classes, Objects and Methods
Introduction to Object-Oriented Concepts in Java
Presentation transcript:

Sanjay Goel, School of Business, University at Albany, SUNY 1 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 2 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 Outline for the Class Arrays

Sanjay Goel, School of Business, University at Albany, SUNY 3 Object-Oriented Programming

Sanjay Goel, School of Business, University at Albany, SUNY 4 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 5 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 6 Object-Oriented Programming Abstraction 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

Sanjay Goel, School of Business, University at Albany, SUNY 7 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 8 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 9 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 10 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 11 Recap

Sanjay Goel, School of Business, University at Albany, SUNY 12 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 13 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 14 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 15 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 16 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 17 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 18 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 19 Objects and Classes

Sanjay Goel, School of Business, University at Albany, SUNY 20 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 21 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 22 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 23 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 24 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 25 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 26 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 27 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 28 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 29 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 30 Objects and Classes Counter Class Let us construct a counter class – What does it do? –increment –resets –gives you a count Let us create a counter 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(); 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 31 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 32 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 33 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 34 Objects and Classes Standard Classes: Palindrome static boolean isPalindrome(String s) { int left = 0; int right = s.length() – 1; while (left < 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