CompSci 6 Programming Design and Analysis
Download
Report
Transcript CompSci 6 Programming Design and Analysis
Reading from Files
import java.io.File;
Declare a file
File fileOfCats = new File(”cats.txt”);
Use file – pass it as an argument to a Scanner
Scanner inscn = new Scanner(fileOfCats);
CompSci 6
12.1
Using Scanner class to read
Import java.util.Scanner;
Look at API
Declare Scanner and bind it to a file (last slide)
Make sure there is input still to read
while(inscn.hasNext())
Read next line
String line = inscn.nextLine();
Read next word
String word = inscn.next();
CompSci 6
12.2
Look at LineNumberer
Snarf L0922
Look at LineNumber.java
Creates a File and a Scanner
Reads one line at a time, counts the lines and prints
out the file with line numbers.
CompSci 6
12.3
Why Inheritance?
shape
Add new shapes easily
without changing much
code
mammal
ScoreEntry
User’s eye view: think and
program with abstractions, realize
different, but conforming
implementations,
don’t commit to something
concrete until as late as possible
CompSci 6
interface or abstraction
Function called at runtime
Concrete subclass
s1 = new Circle();
s2 = new Square();
Abstract base class:
FullHouse, LargeStraight
Shape
Shape
All abstract functions
implemented
Later we'll override
“is-a” view of inheritance
Substitutable for, usable in
all cases as-a
12.4
Example of Inheritance
What is behavior of a shape?
void doShape(Shape s) {
System.out.println(s.area());
System.out.println(s.perimeter());
s.expand(2.0);
System.out.println(s.area());
System.out.println(s.perimeter());
}
Shape s1 = new Circle(2);
Shape s2 = new Square(4);
Shape s3 = new Rectangle(2,5);
doShape(s1); doShape(s2); doShape(s3);
CompSci 6
12.5
Inheritance
Allows you to reuse code
Start with a Class (superclass or parent)
Create child class that extends the class (subclass)
The subclass can:
Use the methods from the superclass or
Override them (use the same name, but the code is
different)
If the subclass redefines a superclass method, can
still call the superclass method with the word
“super” added.
CompSci 6
12.6
Access to Instance Variables(state)
public
private
Any class can access
subclasses cannot access
protected
CompSci 6
subclasses can access
other classes cannot access
12.7
Example (Lab today)
Student (superclass)
DukeStudent (extends Student)
CosmicStudent (extends DukeStudent)
Look at code, what is the output?
CompSci 6
12.8