cse 219 computer science iii objects & abstraction
TRANSCRIPT
CSE 219Computer Science III
Objects & Abstraction
What is abstraction?
• Ignoring certain low-level details of a problem to get a simpler solution– Logical first step in any design– What parts of the problem can be abstracted out to a
higher-level solution?
• Abstraction Techniques:– Type Abstraction– Abstraction by Specification, Iteration Abstraction,
Data Abstraction, etc.
Type Abstraction• Abstract from individual data types to families of
related types– a many to one map
• How can we do this?– Inheritance & Polymorphism
• variables can be polymorphic with respect to the types of objects they contain
• methods can be polymorphic with respect to:– the types of one or more arguments– the return type
• To understand type abstraction, we should first know how objects are managed by Java
Types• A type specifies a well-defined set of values
– example: int, String
• Java is a strongly typed language, what does this mean?– compiled Java programs are guaranteed to be type safe
• except in the case of improper object casting– Generics is one way to avoid this problem
– Ex: ArrayList<TicTacToeServer> threads
= new ArrayList<TicTacToeServer>();
– Java also uses automatic storage management• Helps avoid many errors from C & C++
– the Java compiler checks the code to ensure that every assignment & every call is type correct
• type checking is always done using an object’s apparent type
Java object management• Local variables are stored on the runtime stack
– space is allocated (pushed) when a method is called
– space is de-allocated (popped) when a method returns
– includes object handles for local variables
• Object & class (static) data is stored on the system heap– including instance & static variable handles
• Objects in the heap continue to exist as long as they are reachable from some variable still on the heap or stack– a variable that hasn’t been removed by the garbage collector
– you may force garbage collection using System.gc() or Runtime.gc()
public void someMethod() {
int i = 4;
int[] a = new int[3];
String s = "abc";
s2 = "cba";
}
i 4
Example
s2a
[0, 0, 0]
…
RUNTIME
STACK
…
RUNTIME
HEAP
s
['a', 'b', 'c']
When someMethod completes, what will be garbage collected?
[‘c', 'b', ‘a']
Instance variable of String class of type
char[]
Apparent vs. Actual Type• Each constructed object has an apparent type and an
actual type– due to the rules of polymorphism– only methods of an objects apparent type are available– Java guarantees the apparent type of any object is an ancestor
of its actual type (or the same)– Ex:Vector v = new Vector();// what are v’s apparent & actual types?Object o1 = v;// what are o1’s apparent & actual types?int[] a = {1, 2};Object o2 = a;// what are o2’s apparent & actual types?
• Remember where polymorphism is particularly important?– method arguments & return statements
• like readObject & writeObject
java.util.Hashtable• A Hashtable maps keys to values
– done by mapping Objects (usually Strings) to Objects
– http://java.sun.com/j2se/1.5/docs/api/java/util/Hashtable.html
• Ex:Hashtable dates = new Hashtable();dates.put("TODAY", new GregorianCalendar());dates.put("DDAY", new GregorianCalendar(
1944, Calendar.JUNE,6)); dates.put("ENDOFWORLD", new GregorianCalendar(
2012, Calendar.DECEMBER, 21));…Object obj = dates.get("ENDOFWORLD");Calendar whatDate = (Calendar)obj;DateFormat df =
DateFormat.getDateInstance(DateFormat.MEDIUM);String dateString = df.format(whatDate.getTime());System.out.println(dateString);
OUTPUT: Dec 21, 2012
OUTPUT: What happens if I add dates.put(“NOW", new Date()) ?Potential for Runtime Error!
Hashtable using generics• Alternative: constraint ArrayList, Ex:Hashtable<String, Calendar> dates = new
Hashtable<String, Calendar>();
dates.put("TODAY", new GregorianCalendar());
dates.put("DDAY", new GregorianCalendar(1944, Calendar.JUNE,6));
dates.put("ENDOFWORLD", new GregorianCalendar(2012, Calendar.DECEMBER, 21));
Calendar whatDate = dates.get("ENDOFWORLD");
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
String dateString = df.format(whatDate.getTime());
System.out.println(dateString);
OUTPUT: Dec 21, 2012
OUTPUT: What happens if I add dates.put("NOW", new Date()) ?
Compiler Error!
Which would you prefer, a runtime or compiler error?
Where’s the type abstraction?• The Hashtable class can store any type of Object
• Using generics, a Hashtable object can be constrained to enforce the storage only of a particular type of class
• Inside the Hashtable class:– Object[] keys– Object[] values
java.util.ArrayList class• ArrayList implements List
– can be passed to any method that takes a List object, like:
• Collections.binarySearch– uses Comparator for comparisons
• Collections.reverseOrder• Collections.shuffle• Collections.sort
– uses Comparable for comparisons
• You could also define your own class that implements List– then define the 25 abstract methods in List
Ex: Allowing Employees to be sorted by salary
public class Employee implements Comparable { private String name; private int salary; public Employee(String initName, int initSal) { name = initName; salary = initSal; } public String getName(){ return name; } public int getSalary() { return salary; } public void setSalary(int newSalary) { salary = newSalary; } public int compareTo(Object o) { Employee otherEmp = (Employee)o; if (this.salary == otherEmp.salary) return 0; else if (this.salary > otherEmp.salary) return 1; else return -1; } public String toString() { return name + ", $" + salary; }}
Using ArrayListsimport java.util.*;
public class CollectionsTester { public static void main(String[] args) { ArrayList<Employee> staff
= new ArrayList<Employee>(); Employee e = new Employee("Joe",100000); staff.add(e); e = new Employee("Jane",200000); staff.add(e); e = new Employee("Bob",66666); staff.add(e); Collections.sort(staff); Employee lowestPaid = (Employee)staff.get(0); System.out.println(lowestPaid); }}
Output: Bob, $66666
Where’s the type abstraction?• The Comparable interface provides a standard means
for communication with yet unknown types of objects
• What does that mean?– It means Employee guarantees an abstract, standard mode
of behavior (compareTo)
– So, Collections.sort can sort Employee objects• by calling the Employee class’ compareTo method
• Why is this important to us?– Design patterns use lots of type abstraction
More on actual vs. apparent• So:
– Apparent data type of an object determines what methods may be called
– Actual data type determines where the implementation of a called method is defined
• Starts looking in the actual type class & works its way up
public class Parent {public void print() {
System.out.println("Parent");}
}public class Child extends Parent {
public void print() {System.out.println("Child");
}}public class Driver {
public static void display(Parent p2) {p2.print();
}public static void main(String[] args) {
Parent p = new Parent();display(p);Child c = new Child();display(c);
}} Output?
Parent
Child
Interfaces• Specify abstract methods
– method headers with no bodies
• Ex:public interface ActionListener{public void actionPerformed(ActionEvent ae);
}
• Any class that implements ActionListener guarantees it will define actionPerformed– else a syntax error
• So, Java’s event handling framework can call your event handler (your ActionListener’s actionPerformed)
Abstract Classes• Can specify abstract and concrete methods• Any class that extends an abstract class:
– guarantees it will define all abstract methods, ex:
public abstract class AbstractDie {protected int upValue = 1;protected int numSides = 6;public abstract void roll();public int getUpValue() { return upValue; }
}
public class Die extends AbstractDie {public void roll() {
upValue = (int)(Math.random()*6)+ 1;}
}
Interfaces/Abstract classes & Polymorphism
• Similar rules of polymorphism apply• Objects can have an apparent type of:
– A concrete class
– An interface
– An abstract class
• Ex: public void addActionListener(
ActionListener listener)
• Objects can never have the actual type of an interface or abstract class. Why?– they have no constructors
static vs. non-static• static methods and variables are important to
many design patterns
• What’s the difference?– static (class) methods & variables are shared by
an entire class• one static variable for all objects to share
– Non-static (object) methods & variables are not shared by an entire class
• each object owns its non-static methods & variables
static usage• Can a static method:
– directly call (without using a “.”) a non-static method in the same class?
– directly call a static method in the same class?
– directly reference a non-static variable in the same class?
– directly reference a static variable in the same class?
• Can a non-static method:– directly call (without using a “.”) a non-static method in
the same class?
– directly call a static method in the same class?
– directly reference a non-static variable in the same class?
– directly reference a static variable in the same class?
1 public class Nothing {2 private int nada;3 private static int nothing;45 public void doNada() { System.out.println("NADA"); }6 public static void doNothing()
{ System.out.println("NOTHING"); }78 public static void myStaticMethod() {9 doNada();10 doNothing();11 nada = 2;12 nothing = 2;13 Nothing n = new Nothing();14 n.doNada();15 n.nada = 2;16 }1718 public void myNonStaticMethod() {19 doNada();20 doNothing();21 nada = 2;22 nothing = 2;23 Nothing n = new Nothing();24 n.doNada();25 n.nada = 2;26 }27}