Download presentation
Presentation is loading. Please wait.
Published byAugust Matthews Modified over 9 years ago
1
CompSci 6 12.1 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);
2
CompSci 6 12.2 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();
3
CompSci 6 12.3 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.
4
CompSci 6 12.4 Why Inheritance? Add new shapes easily without changing much code Shape s1 = new Circle(); Shape s2 = new Square(); Abstract base class: interface or abstraction Function called at runtime Concrete subclass All abstract functions implemented Later we'll override “is-a” view of inheritance Substitutable for, usable in all cases as-a shape mammal ScoreEntry FullHouse, LargeStraight 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
5
CompSci 6 12.5 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);
6
CompSci 6 12.6 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.
7
CompSci 6 12.7 Access to Instance Variables(state) public Any class can access private subclasses cannot access protected subclasses can access other classes cannot access
8
CompSci 6 12.8 Example (Lab today) Student (superclass) DukeStudent ( extends Student) CosmicStudent ( extends DukeStudent) Look at code, what is the output?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.