Presentation is loading. Please wait.

Presentation is loading. Please wait.

Class Abstraction and Encaspulation

Similar presentations


Presentation on theme: "Class Abstraction and Encaspulation"— Presentation transcript:

1 Class Abstraction and Encaspulation
How do you design a class knowing that it may be used in many ways? you need to view the class abstractly – irrespective of a specific use for this, you have to think more long-term than the problem at hand In the last chapter, we saw a Student class the implementation was restrictive to the need at hand (a simple searching and sorting program) what else might a Student class need to store and do? deal with a student’s schedule deal with tuition, scholarships, financial aid contain the student’s transcript Think of the class you are to write as a black box – you need to encapsulate all mechanisms inside it to handle user program needs user programs should only be able to access the class via its interface only make public what is needed externally but do not make the interface such that the internal portions of the class are threatened by bad programming in a user class

2 Class Relationships There are relationships between classes – your design should reflect this association – a binary relationship that describes an activity between two classes Student takes a course – there will be some number of Students in a course Teacher teaches a course – usually 1 Teacher teaches a course, but there may be 2-3 if team taught and 0 if no Teacher has yet been assigned these values (0-3, 0-50) specify an association’s multiplicity aggregation – specifies ownership between classes such as a Student has a Name, a Student has an Address if there is a 1-to-1 mapping for an aggregation it is known as a composition such as a Student’s Name while for instance multiple Students may share the same Address aggregations and compositions may exist between objects of the same class such as two Person objects where the relationship is supervisor and supervisee notice with aggregation, instance data of a class can be of other classes you might define an Address class and then use it as an instance datum in the Student class UML provides notation for these types of relationships see the examples on pages

3 Designing a Container Class
Containers store items How do we want to provide access to the items in the container? allow any item to be searched for? if so, should we keep the items in a sorted order for binary search? allow items to only be inserted at the end? do we allow access at both ends making it a line (queue)? do we restrict access to one end (stack)? can specific items be deleted or should we only allow deletion from the accessible end(s)? These questions determine whether our container will be a(n) ordered list (sorted, access anywhere, delete anywhere, insert in order) unordered list (access and delete anywhere, insert at the end for convenience) queue (insert at the end, remove from the front only) stack (insert and remove from one end) What type of item can the container store? we will use an array, so is it an array of ints, an array of Strings? etc

4 Designing a Stack Class
First, let’s assume we want to store only int values the class will have two instance data: elements: int[ ] and size: int We need the following methods no-arg constructor – create an array of a predefined size (e.g., 100), set size to 0 1-arg constructor – create an array whose size is that of the parameter, set size to 0 insert an int (this is known as a push operation) – if room, add the int to the end of the array, increment size remove an int (known as a pop) – if not empty, decrement size and return the int at that location of the array return top item off the stack (known as a peek) – same as pop except don’t decrement size empty – is the array empty? full – is size == size of array? getSize – return size See the class UML on page 378 (they do not include a method for full)

5 Implementing the Stack
public void push(int x) { if(!full()) { elements[size] = x; size++; } else … // output warning public int peek() { if(!empty()) return elements[size-1]; else return -1; } // use -1 to indicate empty public int pop() { int temp = peek(); size--; return temp; }//end Stack class public class Stack { private int[] elements; private int size; public Stack() { elements = new int[100]; size = 0; } public Stack(int s) { if(s>0) elements = new int[s]; else elements = new int[100]; public int getSize() { return size; } public boolean empty() { return size==0;} public boolean full() { return size==elements.length; Note: we could use array doubling if the Stack is full

6 A More Flexible Stack If we want to create a Stack of doubles or Strings, our current implementation is not appropriate we could use several Stacks, one per primitive type but that’s a lot of work There are situations where we want to treat primitive data as objects rather than primitives for instance so that we can create a Stack of Objects rather than a Stack for a given primitive type Java provides for this by having 8 built-in classes for the primitive data types known as wrapper classes the idea is that a wrapper class is used to wrap a primitive datum into an object so that the object can be handled as any object can including for instance to make something like our Stack more flexible we won’t look at altering the Stack implementation as it is more complicated that you might think but we will look at the wrapper classes here we have already seen the use of Integer.parseInt and Double.parseDouble, these are static methods from the Integer and Double classes

7 Wrapper Classes The 8 wrapper classes are Integer, Double, Character, Float, Byte, Short, Long and Boolean, all instantiated using the same syntax Type var = new Type(value); as in Double d = new Double(1.2345); and Integer i = new Integer(100); All of the numeric classes contain methods to return the Object’s internal primitive datum converted to another numeric type using ___Value() where ___ is the primitive type to be returned (e.g., int, double, float, etc) as in d.doubleValue(); i.doubleValue(); (return i as a double) i.intValue(); d.intValue(); (return d as an int) If you are narrowing the value, you may have a loss of precision such as Double d = new Double( ); int i = d.intValue(); // sets i to the maximum int value There are also static methods to convert a String into an Integer or Double (along with the already known ways of converting a String into an int or double) Integer.valueOf(someString)  returns an Integer Double.valueOf(someString)  returns a Double There is also a compareTo method to compare two Objects’ values of the same type

8 Integer and Double UML

9 Boxing and Unboxing The idea of putting a primitive value into an object is referred to as boxing this is handled for you when you instantiate the object, placing the primitive value as the parameter as in int y = 5; Integer x = new Integer(y); the variable x is a boxed version of y Java will automatically box for you Integer x = new Integer(5); Integer x = 5; both result in the same thing, x pointing to an Integer containing the int value 5 The idea of obtaining the primitive datum in a wrap class is known as unboxing Java will automatically unbox for you as well Integer y = new Integer(10); int z = x + y; // x and y are unboxed, added and stored in z

10 BigInteger and BigDecimal Classes
These are two additional useful numeric classes used for storing very large integer and floating point numbers BigInteger bi = new BigInteger(“ ”); BigDecimal bd = new BigDecimal(“ ”); These classes have methods to perform arithmetic operations bi.multiply(new BigInteger(5)); the divide method uses three parameters the divisor, the scale and a rounding mode the scale is the maximum number of decimal digits to retain after division the rounding mode is one of BigDecimal.ROUND_UP, BigDecimal.ROUND_DOWN, BigDecimal.ROUND_FLOOR, BigDecimal.ROUND_CEILING among others The result is a new BigInteger/BigDecimal you can’t store the result of such an arithmetic operation in an ordinary int/double or even an Integer/Double the book offers an example of computing large factorials

11 Strings Revisited The book adds a few more interesting String concepts
you can create a String from a char array char[] c = {‘a’, ‘b’, ‘c’, ‘d’}; String s = new String(c); // s is “abcd” you can split a String into a char array using toCharArray() as in String s = “abcd”; char[] c = s.toCharArray(); // c is now {‘a’, ‘b’, ‘c’, ‘d’} Strings are immutable – you cannot change the value in order to alter the String being stored, you create a new String object String s = “old value”; // s references the String “old value” s = “new value”; // s now references the String “new value” Interned Strings to reduce storage allocation and deallocation, the JVM will retain String values rather than garbage collecting them, in such a case, the String is known as an interned String you can compare two interned Strings using == instead of .equals this can be risky though as if one of the Strings is not yet interned, you can get the wrong value

12 Other Useful String Methods
replace(oldchar, newchar) – returns a version of the String with all versions of ‘oldchar’ replaced by ‘newchar’ replace(oldString, newString) – same but replaces oldString with newString – note that either oldString or newString can be single characters but they must be placed in “” instead of ‘’ as in someString(“a”, “bbb”); - replace all instances of ‘a’ with “bbb” replaceFirst(oldString, newString) – returns a new String in which the first occurrence of oldString is replaced by newString replaceAll(oldString, newString) – same as replaceFirst but replaces all instances of oldString with newString split(delimiter) – returns an array of Strings of this String split up into different Strings wherever the delimiter String is found we might use this for instance to divide a String of words into individual words using “ ” as a delimiter matches(regex) – regex is a String storing a regular expression to compare against this String – returns true or false based on whether there is a match anywhere in this String replaceAll, replaceFirst and split can also use regex

13 More on Strings Aside from System.out.printf, there is also a String.format operation String.format(“specification”, value, value, …); the specification will be similar to what we’ve already seen with printf such as String.format(“%7.2f%4d%-4s”, , 14, “AB”); outputs bb45.56bbbb14ABbb (b = blank) StringBuilder and StringBuffer are classes like String except that they are mutable by inserting or appending characters to the data the difference between the two classes is that the StringBuffer provides synchronized access so that multiple processes accessing the buffer must do so in sequence so that the buffer is not corrupted StringBuilder has 3 constructors (no-arg, an int capacity and a String) StringBuilder has numerous methods including append(char array), append(String), delete(startIndex, endIndex), insert(startIndex, charArray), insert(startIndex, String), reverse, setCharAt(index, char), toString, capacity (return the int capacity), charAt, length, setLength, substring and trimToSize for details see pages


Download ppt "Class Abstraction and Encaspulation"

Similar presentations


Ads by Google