Recitation 9
Download
Report
Transcript Recitation 9
Recitation 9
October 28, 2011
Today’s Goals:
Review abstract classes
Briefly review Java’s Scanner class
Get more practice with scanning
Abstract classes
An abstract class is a hybrid of a class and
an interface
Abstract classes are defined by including
the word “abstract” before the word
“class”:
Abstract classes: Like classes
Has exactly one superclass (Object if none
specified)
Superclass can be either abstract OR nonabstract
Can implement zero or more interfaces
Can contain constructors; these
constructors can call super constructors
Can contain variables, constants, and
implement methods
Abstract classes: Like classes
Abstract classes: Like interfaces
Can’t create an instance of an abstract
class (even if it contains constructors!)
Illegal:
Can implement interfaces but not provide
implementations for the methods in those
interfaces
Legal:
Abstract classes: Unlike classes
or interfaces
Can define abstract methods (i.e. methods
without implementations) and call them (!)
Non-abstract classes
Also called “concrete” classes
If a class is non-abstract, then it provides
implementations of every unimplemented
abstract method from all of its
superclasses, as well as all methods from
all interfaces implemented by all
superclasses
Benefits of abstract classes
Similar to benefits of inheritance
Avoid repeating code
Allow common behaviors
Defer implementation to subclasses
Indicate behavior must be provided, but is
subclass-specific
Prevents the creation of incomplete
objects
Using abstraction
Using abstraction
Using abstraction
Review: java.util.Scanner
import java.util.Scanner;
Create a scanner object to read input from the
console:
Scanner scanner = new Scanner(System.in);
Note: This reads console input, not program
argument input
To get the next string entered by the user (up to
the first whitespace): scanner.next()
To get the next integer entered by the user:
scanner.nextInt()
Recitation Specification
Download Recitation9.zip from the Recitations page
Repeatedly read the next string entered by the user
(scanner.next())
If the user enters “size”, print the size of the stack to the console
If the user enters “pop”, pop the top element off of the stack
If the user enters “triangle”, read in the following 6 integers
(using scanner.nextInt()), create a CartesianTriangle object with
these values, and push it onto the stack
Remember, you need to manually refresh Object Editor
to see these changes (View -> Refresh)
Bonus (for candy): Allow the user to push as many of
these as possible: lines, circles, ovals, rectangles,
squares (all these classes are provided in graphics)