770 likes | 844 Views
CS1515 Revision. Java. Structure. Recap on classes Our ‘project’ Data storage Strings Files Inheritance/Polymorphism GUIs Errors Outside BlueJ. Recap on classes Our ‘project’ Data storage Strings Files Inheritance/Polymorphism GUIs Errors Outside BlueJ. What is a ‘class’?.
E N D
CS1515 Revision Java
Structure • Recap on classes • Our ‘project’ • Data storage • Strings • Files • Inheritance/Polymorphism • GUIs • Errors • Outside BlueJ
Recap on classes • Our ‘project’ • Data storage • Strings • Files • Inheritance/Polymorphism • GUIs • Errors • Outside BlueJ
What is a ‘class’? • Think of it as a description of a real-world item • Sort of like a blueprint or recipe • Ranging from properties to actions Style Steer Brake Colour Size Move
By describing items as classes, we are able to make instances of them • Reading instructions from a blueprint/recipe and making objects from it
We can alter the class to make variations on the created objects • Otherwise we would have the same kind of item • Pretty boring!
Java classes • Java allows us to describe an item with their properties and actions • However, it requires a “unique” way of writing out the description...
An example Java class /** * Write a description of class Item here. * * @author (your name) * @version (a version number or a date) */ public class Item { // instance variables - replace the example below with your own privateint x; /** * Constructor for objects of class Item */ public Item() { // initialise instance variables x = 0; } /** * An example of a method - replace this comment with your own * * @param y a sample parameter for a method * @return the sum of x and y */ publicintsampleMethod(int y) { // put your code here return x + y; } } (BlueJ’s default class)
/** * Write a description of class Item here. * * @author (your name) * @version (a version number or a date) */ public class Item { // instance variables - replace the example below with your own private int x; /** * Constructor for objects of class Item */ public Item() { // initialise instance variables x = 0; } /** * An example of a method - replace this comment with your own * * @param y a sample parameter for a method * @return the sum of x and y */ public intsampleMethod(int y) { // put your code here return x + y; } } • Comments • Useful for telling other programmers what is going on (and to remind yourself!) • Ignored by the compiler
/** * Write a description of class Item here. * * @author (your name) * @version (a version number or a date) */ public class Item { // instance variables - replace the example below with your own private int x; /** * Constructor for objects of class Item */ public Item() { // initialise instance variables x = 0; } /** * An example of a method - replace this comment with your own * * @param y a sample parameter for a method * @return the sum of x and y */ public intsampleMethod(int y) { // put your code here return x + y; } } • Class declaration • The name of the class • Properties and actions go inside the curly brackets (yes, that bracket at the end!) • Generally public...
/** * Write a description of class Item here. * * @author (your name) * @version (a version number or a date) */ public class Item { // instance variables - replace the example below with your own privateint x; /** * Constructor for objects of class Item */ public Item() { // initialise instance variables x = 0; } /** * An example of a method - replace this comment with your own * * @param y a sample parameter for a method * @return the sum of x and y */ public intsampleMethod(int y) { // put your code here return x + y; } } • Instance variables • Properties of the class • Stores details about the object • Should be private...
/** * Write a description of class Item here. * * @author (your name) * @version (a version number or a date) */ public class Item { // instance variables - replace the example below with your own private int x; /** * Constructor for objects of class Item */ public Item() { // initialise instance variables x = 0; } /** * An example of a method - replace this comment with your own * * @param y a sample parameter for a method * @return the sum of x and y */ public intsampleMethod(int y) { // put your code here return x + y; } } • Constructor • Initialises the class (as in when called, creates the object of this class) • Typically sets default values for the properties
/** * Write a description of class Item here. * * @author (your name) * @version (a version number or a date) */ public class Item { // instance variables - replace the example below with your own private int x; /** * Constructor for objects of class Item */ public Item() { // initialise instance variables x = 0; } /** * An example of a method - replace this comment with your own * * @param y a sample parameter for a method * @return the sum of x and y */ publicintsampleMethod(int y) { // put your code here return x + y; } } • Method • Actions of the object • Like functions, but are part of the class
Recap on classes • Our ‘project’ • Data storage • Strings • Files • Inheritance/Polymorphism • GUIs • Errors • Outside BlueJ
Our ‘project’ • I could go over this session as a lecture, but that will be really boring! • Instead, we’ll make a program from scratch which covers (almost) everything you learnt in this course • ... But some slides are required!
... End ...
Recap on classes • Our ‘project’ • Data storage • Strings • Files • Inheritance/Polymorphism • GUIs • Errors • Outside BlueJ
Data storage • Could store music and videos as separate variables... Video video1 = new Video(...); Music music1 = new Music(...); Video video2 = new Video(...); ... • ... But this doesn’t scale well • New variable for new media means recompiling • Searching • Lots of media... • Therefore, we need a smart storage system which can solve these problems
Java provides a lot of storage objects, but we’ll only focus on a tiny portion • Arrays • ArrayLists • HashMaps • ...
Arrays // Creation privateMedia[]database; database = new Media[10]; • // Write database[0] = media1; database[1] = media2; ... database[9] = media10; • // Read • System.out.println(database[0]); • // Creation privateMedia[]database; database = {media1, media2, ... , media10}; • // Write • database[0] = media1; • database[1] = media2; • ... • database[9] = media10; • // Read System.out.println(database[0]); • Collection of any class/primitive • Fixed size • Simple read/write • Limited methods • length
Good as a database? • No (but it’s better than a collection of member variables!) • Don’t know how many media items will be in the database • Fixed length is bad for this • Have to recreate array for new entries/removing old entries
ArrayList // Import (top of file) importjava.util.ArrayList; • // Creation privateArrayList<Media> database = null; database = newArrayList<Media>(); // Add database.add(media1); • database.add(media2); ... // Get database.get(index); • // Remove database.remove(index); • Collection of any class (no primitives – need object version) • Need to import ArrayList • not included by default • Variable size
Good as a database? • Yes! • Variable size means user can add as many music tracks and videos as she likes • Contains methods to help with organisation • size() • indexOf() • contains() • ...
HashMap // Import (top of file) importjava.util.HashMap; • // Creation privateHashMap<Integer, Media> database = null; database = newHashMap<Integer, Media>(); // Add database.put(index1, media1); • database.put(index2, media2); ... // Get database.get(index); • // Remove database.remove(index); • Collection of two classes (no primitives – need object version) • Behaves like an ArrayList, but uses Key, Value pairs • Use a key to find the value • Need to import HashMap • not included by default • Variable size
Good as a database? • Yes! • Same advantages as ArrayList, but does not have as many useful helper methods • Biggest advantage over ArrayList is being able to find a value by knowing the key • Could have written a lookup ourselves, but why reinvent the wheel?
importjava.util.HashMap; • /** • * Write a description of class Database here. • * • * @author Michael Gibson • * @version 1 • */ • publicclass Database{ • privateHashMap<Integer, Media> database = null; • /** • * Constructor for objects of class Database • */ • public Database() • { • database = newHashMap<Integer, Media>(); • } • publicvoidaddMedia(int id, Media media){ • database.put(id, media); • } • publicvoidremoveMedia(int id){ • database.remove(id); • } • }
If we compile now... • BlueJ will complain about Media not existing • To fix this, create a new class called Media • We’ll get back to this class later...
Recap on classes • Our ‘project’ • Data storage • Strings • Files • Inheritance/Polymorphism • GUIs • Errors • Outside BlueJ
Strings • Fundamentally an array of chars • Not really easy to write sentences with • Or make modification to... privatechar[]sentence = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’};
Java has a built-in class to help with this – the String class • Provides numerous methods to help with formatting and construction (String s) • equals(s) • equalsIgnoreCase(s) • startsWith(s) • toUpperCase() • split(s) • ... privateStringsentence= “Hello”;
Formatting • We can use ‘escape characters’ to format a String • ‘\n’ = New line • ‘\t’ = Tab • ‘\’’ = ‘ • ‘\”’ = “ • ‘\\’ = \ • ...
Putting the escape characters in a String alters its appearance on the screen • System.out.println("Type\tName\tArtist/Director\tLength\tRating\tComment\n“);
Concatenation • Can create new Strings by adding existing Strings together • "<music>" + "\t" + name + "\t" + artist + "\t" + time + "\t" + rating + "\t" + comment;
Something to watch out for... • Strings cannot (should not!) be compared with other Strings like primitives • s1 == s2 will give unexpected results! • This is because the == operator checks if the references are the same • i.e. if the memory locations are the same • Therefore, always use s1.equals(s2)
Recap on classes • Our ‘project’ • Data storage • Strings • Files • Inheritance/Polymorphism • GUIs • Errors • Outside BlueJ
Files • It’s nice to be able to save our work and refer to it later on • Imagine having to rewrite essays when you need it? • Me writing these slides right now!? • We can save our work as files so that we can read/edit them later on • Even in different programs
Most programs write objectdata to files so that they can be processed quicker • Even adds a layer of security to the data (even if it is proprietary...) • Doesn’t make the file always friendly with other programs...
Er... no thanks! • Instead, we’ll save our files as human-readable text • Much easier to understand! • Can edit it using any text editor
TextReader/TextHandler • SimpleIO provides us with TextReader to read files and TextHandler to write files • Processes each line of a file as a String • Fairly simple to setup and use...
TextReader // Import (top of file) importsimpleIO.TextReader; • // Creation • private TextReader reader = new TextReader(“file.txt”); // Read • String s = reader.readLine(); • while(s != null){ • ... • s = reader.getLine(); • } // Close reader.close() • “file.txt” can be any file • Can also include a path • If this is blank, a dialog box will appear asking for a file • ... refers to file processing • remember to get the next line when finished, otherwise this’ll loop forever! • Need to close the file after finishing to free it
TextWriter // Import (top of file) importsimpleIO.TextWriter; • // Creation • private TextWriter writer = new TextWriter(“file.txt”); // Write • writer.writeLine(“Any String here”); // Close writer.close() • “file.txt” can be any file • Can also include a path • If this is blank, a dialog box will appear asking for a file • Clears the file when opened, so make sure any previous work is saved! • “file.txt” can be a literal String (like it is now) or a String object • Need to close the file after finishing to free it
Back to our program... • We want to store our media for future reference • From what we learnt about Strings and files, we can store this as a collection
import java.util.HashMap; • importsimpleIO.TextReader; • importsimpleIO.TextWriter; • /** • * Write a description of class Database here. • * • * @author Michael Gibson • * @version 1 • */ • public class Database{ • private HashMap<Integer, Media> database = null; • private String file = "database.txt"; • private static int id = 0; • ... • privatevoidreadFile(){ • TextReader reader = newTextReader(file); • String s = reader.readLine(); • while(s != null){ • String data[] = s.split("\t"); • intmediaID = Integer.parseInt(data[0]); • int rating = Integer.parseInt(data[5]); • if(data[1].equals("<music>")){ • Music music = new Music(mediaID, data[2], data[3], data[4], rating, data[6]); • database.put(mediaID, music); • }else if(data[1].equals("<video>")){ • Video video = new Video(mediaID, data[2], data[3], data[4], rating, data[6]); • database.put(mediaID, video); • } • if(mediaID >= id){ • id = mediaID + 1; • } • s = reader.readLine(); • } • reader.close(); • } • }
import java.util.HashMap; • importsimpleIO.TextReader; • importsimpleIO.TextWriter; • /** • * Write a description of class Database here. • * • * @author Michael Gibson • * @version 1 • */ • public class Database{ • ... • private voidwriteFile(){ • TextWriter writer = newTextWriter(file); • for(int id: database.keySet()){ • writer.writeLine(id + "\t" + database.get(id)); • } • writer.close(); • } • } • readFile() • Splits each line in the file by tabs • Creates a new media object (video or music) depending on its type (data[1]) • Adds it to the database • writeFile() • Writes the database (HashMap) to file
Recap on classes • Our ‘project’ • Data storage • Strings • Files • Inheritance/Polymorphism • GUIs • Errors • Outside BlueJ
Inheritance • If you haven’t noticed yet, we’re expanding the Inheritance example from the lecture slides... • So (hopefully) this should be a breeze!
Why inheritance again? • If we have similar items, we want them to share as many properties andactions • Reduces code repetition • Reduces maintenance • Easier to create new kinds of items (extensible)
/** • * Write a description of class Media here. • * • * @author (your name) • * @version (a version number or a date) • */ • public abstract class Media • { • protected String name, comment; • protectedint id, rating; • /** • * Constructor for objects of class Media • */ • public Media(int id, String name, int rating, String comment) • { • this.id = id; • this.name = name; • this.rating = rating; • this.comment = comment; • } • public String getName(){ • return name; • } • publicintgetRating(){ • return rating; • } • public String getComment(){ • return comment; • } • public abstract String toString(); • }