Class Notes (1,100,000)
US (490,000)
Cornell (1,000)
CS (100)
CS 2110 (30)
Gries (30)
Lecture 7

CS 2110 Lecture Notes - Lecture 7: Abstract Data Type, Abstract Type


Department
Computer Science
Course Code
CS 2110
Professor
Gries
Lecture
7

This preview shows half of the first page. to view the full 3 pages of the document.
Lecture 7 - Abstract and Interfaces
oA Little Geometry!
When using a GUI, a shape’s position is given by the top left corner of the
box it can be inscribed in
oAbstract classes/methods
Problem!
We don’t like the creation of Shape objects
Why? Because they are too abstract
Could be any shape
What if we wanna make an array of Shapes, but we
could have triangles, squares, circles, dodecagons??
How do we avoid this
public abstract class Shape(...) {...}
The abstract prevents the user from using the Shape
constructor
If you tried to call the constructor you get a Static Error
A concrete class is required
If it was just public class Shape(...) {...}
We can call the constructor and run into problems
So this forces the user to construct objects of the right type
Suppose we have in the abstract class Shape a sumAreas() method
This would involve taking a list of Shapes and adding the area of
each of them
If we called a helper function for each shape, we get a problem:
Because the sumAreas method is defined in Shape but the
area method is NOT, it will not use the bottom up rule
We make an area method in Shape
public abstract double area();
Now it will go down the chain and use the bottom up rule for the
correct shape
Abstract summary
To make it impossible to create an instance of a class C, make C
abstract:
public abstract C {...}
In an abstract class, to require each subclass to override method
m(...) make m abstract:
public abstract int m(...);
Abstract classes can be used to “define” a type (abstract data type)
If every method in the class is abstract, it defines a type
Example Stack
public abstract class Stack {
public abstract boolean isEmpty();
public abstract void push(int k);
public abstract int pop();
Then we make subclasses of “types” of stacks
Stacks of ints, booleans, arrays,...
find more resources at oneclass.com
find more resources at oneclass.com
You're Reading a Preview

Unlock to view full version