Xiaoying Gao Computer Science Victoria University of Wellington Copyright: Xiaoying Gao, Peter Andreae, Victoria University of Wellington Create Objects, Assignment 3 COMP 102 # T2
© Peter Andreae COMP 102 9:2 Menu Assignment 3 Q1 Designing a program with multiple methods Methods that call methods from the same class. Assignment 3 Q2 Create objects Call methods from objects Administrivia:
© Xiaoying Gao, Peter Andreae COMP102 8:3 A class with fields and constructor import ecs100.*; public class BankAccount{ //simplified version of the exercise private String name; private double balance; public BankAccount(String n){ this.name = n; this.balance = 0.0; } public void deposit(double x){ this.balance = this.balance + x; } public void withdraw(double x){ this.balance = this.balance - x; } public void statement(){ UI.println(this.name + " $"+this.balance); } }
© Xiaoying Gao, Peter Andreae COMP102 8:4 Use the class to create new objects public class NewObjects{ public void createNewObj(){ BankAccount b1 = new BankAccount("Alice"); b1.deposit(100); BankAccount b2 = new BankAccount("Bob"); b2.deposit(200); b1.withdraw(50); b2.statement(); b1.statement(); }
© Xiaoying Gao, Peter Andreae COMP102 8:5 Why objects A new data type: group data together Group data and methods together Data fields: states, characteristics, important data of objects Methods: use the fields, update the fields Different objects co-exist The same class reused differently for different objects …
© Xiaoying Gao, Peter Andreae COMP102 8:6 Call a method In the same class Normally use “this” In another class Static Call using class name Not Static Create objects, call from objects
© Xiaoying Gao, Peter Andreae COMP102 8:7 Data type int, long double, float char boolean String Scanner Color BankAccount Butterfly CartoonFigure
© Xiaoying Gao, Peter Andreae COMP102 8:8 A class A class defines a new data type Constants belong to class Static methods belong to class Data fields: save the states (characteristics, important data) of objects Constructor Methods Use data fields, to access/process/update the data fields
©Xiaoying Gao, Peter Andreae COMP102 8 :9 Examples of objects and their methods Butterfly program Each butterfly is represented by an object which stores the state of the butterfly (position, wing state, direction) Butterflies have methods move(double dist) and land() CartoonFigure program Each cartoon figure is represented by an object which stores the state of the cartoon figure (image, position, direction facing, smile/frown). CartoonFigure objects have methods move(double dist) smile()frown() left()right() talk(String words)
©Xiaoying Gao, Peter Andreae COMP102 8 :10 How to call these methods You can not do these: UI.move(200). this.move(200) Butterfly.move(200); Call a static method in other class: (Classname.method) UI.println(“hi”); System.currentTimeMillis(); Math.pow(3,2); Call a method in the same class this.measureTime(“3*2=6 ”); Call a non-static method in other class Create an object Call methods from an object
©Xiaoying Gao, Peter Andreae COMP102 8 :11 Using objects If the variable bf1 and bf2 had Butterfly objects, you could do: public void showButterfly(){ Butterfly bf1 = ????? Butterfly bf2 = ????? bf1.move(10); bf2.move(20); bf1.land(); bf2.move(20); bf1.move(5); } Problem: How do you get a Butterfly object into the variables? Nothing new here: Just standard method calls!
©Xiaoying Gao, Peter Andreae COMP102 8 :12 Creating Objects Need to construct new objects: New kind of expression: new Butterfly bf1 = new Butterfly(…) Constructors are like method calls that return a value. have ( ) may need to pass arguments returns a value – the new object that was constructed. Constructors are NOT method calls there is no object to call a method on. must have the keyword new name must be the name of the class Calling the constructor 100, 300) Creates a new object, which is put into bf1
©Xiaoying Gao, Peter Andreae COMP102 8 :13 Parameters of methods and constructor Documentation of a class: Specifies the methods: name type of the return value (or void if no value returned) number and types of the parameters. voidmove (double dist) moves the butterfly by dist, in its current direction. Specifies the constructors: number and types of the parameters (name is always the name of the class, return type is always the class) Butterfly(double x, double y) requires the initial position of the butterfly Bluej lets you see the documentation of your classes
©Xiaoying Gao, Peter Andreae COMP102 8 :14 Example: Butterfly Grove program public class ButterflyGrove{ /** A grove of Butterflies which fly around and land */ public void oneButterfly(){ Butterfly b1 = new Butterfly(50*Math.random(), 20); b1.move(5); b1.move(10); b1.move(15); b1.move(10); b1.land(); } } public void twoButterflies(){ Butterfly b1 = new Butterfly(50*Math.random(), 20); b1.move(5); b1.move(10); b1.move(15); Butterfly b2 = new Butterfly(80, 40*Math.random()); b1.move(10); b2.move(10); b1.move(10); b2.move(10); b1.move(10); b2.move(10); b1.move(10); b1.land(); b2.move(20); }
©Xiaoying Gao, Peter Andreae COMP102 8 :15 The main method A complete program should have a main method What to do when a program starts You need a main method To run a program without BlueJ To run a java program from command line To generate a stand alone executable file
©Xiaoying Gao, Peter Andreae COMP102 8 :16 The main method import ecs100.*; import java.awt.Color; public class ColorExample { public void colorMethod(){ Color c1 = new Color(200, 200, 50); UI.setColor(c1); UI.fillOval(50, 50, 50, 50); Color c2 = c1.brighter(); UI.setColor(c2); UI.fillOval(100, 50, 50, 50); String s = c2.toString(); UI.println(s); } public static void main(String[] args){ ColorExample ce = new ColorExample(); ce.colorMethod(); }
©Xiaoying Gao, Peter Andreae COMP102 8 :17 The main method Create an object Call a method What if there is not a constructor Use the default constructor All classes have a default constructor No parameters Do nothing in the body public ColorExample() { }
Read a Story & Get Free Coffee! Take a 15 minute break to participate in our online study exploring readers’ emotional response to interactive stories. You will be rewarded with fun experience and a $5 Coffee Voucher in a Wishbone café! To participate & claim your voucher please at:
© Peter Andreae COMP 102 9:19 Where we have been Designing methods: Statements Variable declarations Assignment statements and expressions Method calls (passing arguments) if ( … ) { … } and if ( … ) { … } else { … } while ( … ) { … } Defining methods (with parameters) (vs calling methods) Input Parameters Scanner and System.in JOptionPane Output System.out DrawingCanvas
© Peter Andreae COMP 102 9:20 HouseDrawer Draw a street of houses of different random sizes: assume size is between 100 and 150
© Peter Andreae COMP 102 9:21 HouseDrawer Draw a street of houses of different sizes:
© Peter Andreae COMP 102 9:22 Designing a program: filling in details public class HouseDrawer{ /** Draw a street of multi-story houses */ public void drawStreet( ){ // draw a house at ( 50, 400 ), ? high // draw a house at ( 100, 400 ), ? high // draw a house at ( 150, 400 ), ? high // draw a house at ( 200, 400 ), ? high // draw a house at ( 250, 400 ), ? high // draw a house at ( 300, 400 ), ? high // draw a house at ( 350, 400 ), ? high // draw a house at ( 400, 400 ), ? high } How do we specify the positions of the houses? How do we work out a random height?
© Peter Andreae COMP 102 9:23 Random numbers Math.random() computes and returns a random double between 0.0 and 1.0 To get a random number between min and max: multiply random number by (max-min) add to min: (100 + Math.random() * 50) gives a value between and This is an expression: can assign it to a variable to remember it can use it inside a larger expression can pass it directly to a method
© Peter Andreae COMP 102 9:24 Designing a program: filling in details public class HouseDrawer{ /** Draw a street of multi-story houses */ public void drawStreet( ){ // draw a house at ( 50,400), ? high // draw a house at (100,400), ? high // draw a house at (150,400), ? high // draw a house at (200,400), ? high // draw a house at (250,400), ? high // draw a house at (300,400), ? high // draw a house at (350,400), ? high // draw a house at (400,400), ? high } How do we draw a house?
© Peter Andreae COMP 102 9:25 “Wishing Programming" public class HouseDrawer{ /** Draw a street of multi-story houses */ public void drawStreet( ){ // draw a house at ( 50,400), ? high this.drawHouse( 50, 400, (100+Math.random()*50) ); // draw a house at (100,400), ? high this.drawHouse( 100, 400, (100+Math.random()*50) ); } } When there isn't a method to do what you want, wish for one! Make up a descriptive method name Work out what values it will need Call it on the same object Then go and define the method Have to be your own fairy godmother!!
© Peter Andreae COMP 102 9:26 Fulfilling the wish: defining the method public class HouseDrawer{ : public void drawStreet( ){ … : /** Draw a multi-story house with windows */ public void drawHouse(double mid, double bot, double ht){ // Draw the rectangle of the house and the roof UI.drawRect(…….); UI.drawLine(…….); // Draw the windows } }
© Peter Andreae COMP 102 9:27 Drawing the outline public class HouseDrawer{ : public void drawStreet( ){ … : /** Draw a multi-story house with windows */ public void drawHouse(double mid, double bot, double ht){ // Draw the rectangle of the house and the roof double wd = 46; double left = mid – wd/2; double right = mid + wd/2; double top = bot - ht; double tip = top – wd*2/3; UI.drawRect( left, top, wd, ht); UI.drawLine( left, top, mid, tip); UI.drawLine( right, top, mid, tip); // Draw the windows } } Work out what variables we need, (mid,bot) ht wd Use them. Declare and initialise them,
© Peter Andreae COMP 102 9:28 Wishing for windows public class HouseDrawer{ : public void drawHouse(double mid, double bot, double ht){ double wd = 46; double left = mid – wd/2; double right = mid + wd/2; double top = bot – ht; double tip = top – wd*2/3; UI.drawRect( left, top, wd, ht); UI.drawLine( left, top, mid, tip); UI.drawLine( right, top, mid, tip); // Draw the windows: this.drawWindow(….); } } (mid,bot) ht wd "Wish" for a drawWindow method How do we specify a window? - what could vary from window to window?
© Peter Andreae COMP 102 9:29 Wishing for windows public class HouseDrawer{ : public void drawHouse(double mid, double bot, double ht){ double wd = 46; double left = mid – wd/2; double right = mid + wd/2; double top = bot – ht; double tip = top – wd*2/3; UI.drawRect( left, top, wd, ht); UI.drawLine( left, top, mid, tip); UI.drawLine( right, top, mid, tip); // Draw the windows: double winL = mid - wd/4; double winR = mid + wd/4; double lev1 = bot - ht/4; double lev2 = bot – 3* ht/4; this.drawWindow(winL, lev1, wd/3); this.drawWindow(winR, lev1, wd/3); this.drawWindow(winL, lev2, wd/3); this.drawWindow(winR, lev2, wd/3); } (mid,bot) ht wd Now have to deliver on the "Wish"
© Peter Andreae COMP 102 9:30 Fulfilling the wish, again public class HouseDrawer{ : public void drawStreet( ){ … : public void drawHouse( double mid, double bot, double ht){ : /** Draw a window */ public void drawWindow(double midX, double midY, double sz){ double rad = sz/2; UIdrawRect(midX-rad, midY-rad, sz, sz); UI.drawLine(midX-rad, midY, midX+rad, midY); UI.drawLine(midX, midY-rad, midX, midY+rad); } }
© Peter Andreae COMP 102 9:31 Where have we been? Structured Design / “Wishful programming” Break the problem into managable, separable chunks One method for each chunk Work out the “interface” to each chunk: what information the method needs (the parameters) what information the method will return, if any. Use the chunk by calling the method, specifying arguments calls to a method in the same class usually called on the this object. Define the chunk by defining the method, specifying the parameters and the return type. specifying the actions in the body
© Peter Andreae COMP 102 9:32 main method Running a program independently of BlueJ Don't have an object! Only have the class. Need a method that doesn't need an object, has a standard name can take any number of arguments!!! public static void main(String… args){ HouseDrawer hd = new HouseDrawer(); hd.drawStreet(); } > java HouseDrawer
© Peter Andreae COMP 102 9:33 Calling Methods: How does it work? An object is like a filing card in a filing box, marked with its category (class) and an identifier A method definition is like a master copy of a worksheet Every time you call a method on an object, you make a copy of the worksheet, and work through it. The identifier of the object is copied into the box called “this”. Parameters of the method are like boxes at the top of the worksheet: you copy the arguments into the boxes. When you have finished the worksheet, you throw it away, along with any information stored in its boxes.