340 likes | 359 Views
Learn the key concepts of Object-Oriented Programming (OOP) in Java, including Abstraction, Encapsulation, Inheritance, and Polymorphism. Explore classes, arrays, variables, declarations, and more!
E N D
MSI 692: Special Topics in Information Technology Lecture 5: Objects Sanjay Goel University at Albany, SUNY Fall 2004
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
Object-Oriented ProgrammingFeatures • There are four features of object-oriented programming • Abstraction • Encapsulation • Polymorphism • Inheritance
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.
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
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
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.
Object-Oriented ProgrammingClass Types • Class types is defined as: class classname {members of the class} class Fruit { int grams; int totalCalories () { return grams * 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
RecapArrays and Variables • Arrayis 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.
RecapDeclaration 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]
RecapIndexing 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
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 < 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
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 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
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
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 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
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.
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.
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.
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.
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
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
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.
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
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
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)
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.click(); 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
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
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.
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.
Objects and ClassesStandard Classes: Palindrome Let us create a class called person: Class Person { int age; String name String sex } Passing 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; }