# 12/06/2014F21SF SEF L21 F21SF Software Engineering Foundations 2 A first Object-oriented program Monica Farrow EM G30 Material.

## Presentation on theme: "12/06/2014F21SF SEF L21 F21SF Software Engineering Foundations 2 A first Object-oriented program Monica Farrow EM G30 Material."— Presentation transcript:

12/06/2014F21SF SEF L21 F21SF Software Engineering Foundations 2 A first Object-oriented program Monica Farrow EM G30 email : M.Farrow@hw.ac.uk Material available on Vision Dept of Computer Science

12/06/2014F21SF SEF L22 Topics Developing a first object-oriented program, looking at Data types Instance variables Constructors Methods Arithmetic operators UML class and sequence diagrams are introduced

12/06/2014F21SF SEF L23 A first object-oriented program Wed like a program to meet this specification: For any car, we know how much fuel can be held in a full tank, and the average miles per gallon. Wed like to know how far a car should be able to travel on a full tank. British manufacturers provide the tank size in litres but fuel consumption in miles per gallon! Sample input Type of car = Ford Ka, Tank size in litres = 40, average miles per gallon = 33.6 Sample output A Ford Ka can travel 295.68 miles on a full tank Developing the program In this lecture we see how to design an object-oriented solution

12/06/2014F21SF SEF L24 Object Classes The idea of a class forms the basis of object-oriented programming in Java We model real world objects in a computer program Everything about one type of object is encapsulated in the one place – the class For this program, a Ford Ka is an object of the Car class Another Car object might be a Volkswagen Sharan Our program should work for any type of car. We are aiming for a program to be Readable, Maintainable, well-designed, Robust Should not contain duplicate blocks of code

12/06/2014F21SF SEF L25 Program structure For a small problem, designing using objects makes a program much larger than it would otherwise be We are laying foundations for much larger programs The first time you see an object-oriented program, it looks quite complicated Well keep reinforcing class design so that you absorb the ideas over time

12/06/2014F21SF SEF L26 Classes in a typical program Typically an application will have A main method, often in a separate class, to start the application A class for each type of object. The class contains attributes and functions, for one or more distinct objects of this type. E.g. Car, Person, Course Possibly a class for each collection of objects (e.g. all cars in a garage, all staff in a company) A manager class. The main functionality of the program is handled here. This often uses a Graphical User Interface. We show the classes and the associations between them using a UML class diagram

12/06/2014F21SF SEF L27 Example UML class diagram Classes are shown in rectangles The associations between the classes are shown by lines The lines may be directional, showing which classes know about the other classes E.g. Customer class knows about the Account class but not the CustomerCollection CustomerCollection only knows about Customer objects Account Customer MainClass Process Transactions Account Collection Customer Collection

12/06/2014F21SF SEF L28 Object-oriented solution With object-oriented design, we look at the problem and see what objects we have, what attributes the objects have and what operations need to be performed on the object One obvious object in todays program is a Car Attributes could be : the size of the tank, the average mpg, the model Operations : find distance travelled on full tank. i.e. Tank size converted to gallons and multiplied by avg mpg

12/06/2014F21SF SEF L29 CRC Card for Car class We can show the Responsibilities of the class using a CRC card. CRC stands for Classes, Responsibilities and Collaborators (Collaborators covered later) Return model details Calculate and return the distance that the car can travel on a full tank Maintain data about model, tank size and mgp Responsibilities Car

12/06/2014F21SF SEF L210 Todays program Will consist of A class containing a main method This is where the program starts Today it will also handle the main functionality of the program It will simply create a Car object, obtain that cars data and display results A Car class managing everything about cars. This is a typical class, although very small MainClassCar

12/06/2014F21SF SEF L211 Objects and classes Wed like to produce a single template or class which enables us to hold car details and find distance information One Car class This is the Source file that we write in java A text file named Car.java Our program will use the Car class to create one or more Car objects, then find the distance information E.g. Ford Ka, tank size 40 litres, mpg 33.6 E.g. Mercedes Benz E280, tank size 65 litres, mpg 22

12/06/2014F21SF SEF L212 A class consists of A name, which should start in upper case e.g. Car Instance variables to describe the data about a particular object Eg. Model, tank size etc A constructor, to create the object and assign values to the instance variables E.g. tankSize = 66 Methods, to perform operations on the data. These are similar to functions and subroutines in other languages E.g. find out how far the car can travel E.g. tell us what the tank size is

12/06/2014F21SF SEF L213 Outline UML Class diagram MainCar main(..) Car model tank size manufacturers mpg create car with initial data return the model return the estimated distance data operations (doing things with the data)

12/06/2014F21SF SEF L214 Outline UML sequence diagram myCar :Car main() Create a car Get the distance Get the model of the car Standard output Use standard output to display results the long rectangle represents the main method objects methods of a class calling the methods (vertical order is important)

12/06/2014F21SF SEF L215 Class outline public class Classname { //instance variables //constructor(s) //methods } So a Car class starts public class Car

12/06/2014F21SF SEF L216 Instance variables Instance variables descibe the data about a particular object. They have an access modifier, a data type, a name (identifier), and contain a value e.g. private String model; The access modifier is usually private, meaning that other classes cant use the variable directly The data type (e.g. String) describes the data (see next slide) The identifier should be a meaningful name, starting lower case by convention Declare instance variable all together at the start or the end of the class. I prefer the start, because you can see them easily The value is stored later.

12/06/2014F21SF SEF L217 Java data types Java has a set of primitive data types including int for integers double for real numbers char for single characters boolean for true/false values See http://download.oracle.com/javase/tutorial/java/nutsandb olts/datatypes.html for more details http://download.oracle.com/javase/tutorial/java/nutsandb olts/datatypes.html There is a special String class for text, which provides many useful features Other more complex objects can be represented by classes, such as the Car class

12/06/2014F21SF SEF L218 Car class – instance variables //model private String model; //tank size in litres private int tankSize; // miles covered per gallon //(manufacturer's figures) private double manfMPG;

12/06/2014F21SF SEF L219 To create an object, use the class constructor The constructor has the SAME NAME AND CASE as the class (starting with Upper Case) The constructor should initialise the instance variables (data) either to suitable default values or from data passed to the constructor as parameters CONSTRUCTOR

12/06/2014F21SF SEF L220 Creating an object We will create objects today in the main method, using a statement that looks like this: Car myCar = new Car (Ford Ka, 40, 33.6); Data type Variable name Assign RHS value to LHS variable Create a new object Call the Car constructor Provide the data values as parameters

12/06/2014F21SF SEF L221 Executing this call to the Car constructor The line below, in the main method, calls the Car constructor and provides the data for this car. Car myCar = new Car (Ford Ka, 40, 33.6); The Car constructor, in the Car.java class, starts with a header like this: public Car (String model, int tank, double mpg) Means that any other class can use the constructor Class name, starts upper case Type and name used for parameters

12/06/2014F21SF SEF L222 Car class - constructor The constructors task is to create the object, usually assigning values to the instance variables. The body of the constructor consists of statements public Car(String model, int tank, double mpg) { //store values supplied in parameters into //instance variables this.model = model; tankSize = tank; manfMPG = mpg; }

12/06/2014F21SF SEF L223 this In the constructor We initialise the instance variables, often from a parameter value One of the parameters has the same name as an instance variable. We use this to refer to the instance variable tankSize = tank Instance variable parameter this.model = model Instance variable parameter

12/06/2014F21SF SEF L224 The program so far : MainCar class public class MainCar { public static void main (String[] args) { //create a Car Car myCar = new Car(Ford Ka, 40, 33.6); } //end main method } //end class

12/06/2014F21SF SEF L225 The program so far : Car class public class Car { //instance variables private String model; private int tankSize; private double manfMPG; //constructor public Car(String model, int tank, double mpg) { this.model = model; tankSize = tank; manfMPG = mpg; }

12/06/2014F21SF SEF L226 Running the program so far If we were to run the program as it is The program starts in the main method The first statement declares a variable of type Car and with name myCar will assign a value to myCar, using = The value is a new Car object, created by executing the Car constructor Control passes to the Car constructor Each statement in the Car constructor is executed in turn, assigning values to the instance variables for an object named myCar Control passes back to the next statement in the main method At the moment there isnt one!

12/06/2014F21SF SEF L227 After using the constructor myCar model Ford Ka tankSize 40 manfMPG 33.6 We have an object of the Car class called myCar. The instance variables have got values stored in them

12/06/2014F21SF SEF L228 UML Sequence diagram This diagram shows action starting from the black circle. The arrow from the black circle represents the main method in the MainCar class being called. The long rectangle represents the main method. The arrow from the main method shows the Car constructor being called and a new Car object, called myCar, being created. The sequence of events is shown starting at the top and moving downwards. myCar :Car main() new Car(Ka,40,7.4)

12/06/2014F21SF SEF L229 Using the Car class in the main method We have created an object of class Car, using the constructor Then we can use methods of the Car class To be able to print the line A Ford Ka can travel 295.68 miles on a full tank we need get the name of the model and the number of estimated miles. The rest of the text is the same for all cars So the Car class must contain methods to provide this information

12/06/2014F21SF SEF L230 Using the Car class in the main method Assuming suitable methods exist in the Car class, the main method will look like this: //create object Car myCar = new Car ("Ford Ka", 40, 33.6); //get model name and store in a local variable calle model String model = myCar.getModel(); //get estimated distance and store in a local variable called distance double distance = myCar.estimateDistance(); //print the details to standard output System.out.println("A " + model + " can travel " + distance + " miles");

12/06/2014F21SF SEF L231 Points to note on previous code To call a method from a different class, attach the method name to an object with a period (full stop) E.g. myCar.getModel() The method runs, using the values of the instance variables that belong to myCar as opposed to any other cars that might have been created In the main method, we declare temporary local variables of the correct type to store data in. e.g. model, distance We can concatenate (join) Strings and variable values using the + sign

12/06/2014F21SF SEF L232 The getModel method in the Car class Any parameters in brackets (none) public String getModel() { return model; } Access modifier method name, starts lowercase Return statement Return type Curly brackets enclose method body One of the instance variables

12/06/2014F21SF SEF L233 Car class – methods to get info out //Return model public String getModel() { return model; } //estimate distance car can travel public double estimateDistance() { //there are 0.22 gallons per litre return tankSize * manfMPG * 0.22; }

12/06/2014F21SF SEF L234 ARITHMETIC OPERATORS Operators are: + : addition, - : subtraction, * : multiplication, / : division (different effect for integers/reals) % : remainder (only for integers, also called mod) ++, += : incrementation operators --, -=: decrementation operators

12/06/2014F21SF SEF L235 What goes in methods Methods make the program do things Methods can, and frequently do, call other methods The code inside methods follows the basic ideas for procedural programs: Sequence (simple statements including calculations) Selection (branching) Repetition (loops) Many methods provide an answer. i.e. they return a value

12/06/2014F21SF SEF L236 Running a program with multiple classes Compile the main method Any associated classes will also be compiled Run the main method Each statement in the main method is executed in turn, passing control to constructors and methods when necessary. At the end of each method, control is passed back to the calling method.

12/06/2014F21SF SEF L237 UML Sequence diagram In the sequence diagram on the next page The sequence of events is shown starting at the top and moving downwards The named rectangles represent objects. The empty rectangles represent the methods. The dotted vertical lines are lifelines showing how long the object is in existence for Here, until the end of the program

12/06/2014F21SF SEF L238 A more detailed Sequence diagram myCar :Car main() new Car(Ka,40,7.4) distance= estimateDistance() model = getModel() Standard output println(message incl model & distance)

12/06/2014F21SF SEF L239 UML class diagram In the UML class diagram on the next slide, each class is divided into 3 sections Class name at the top Instance variable name and type in the middle section Note that in the diagram the type comes last, in java you will see that the type comes before the name Methods, including constructors, in the final section – again, return types are shown after the method name

12/06/2014F21SF SEF L240 Class diagram MainCar main(..) Car - model : String - tankSize : int - manfMPL : double + Car(model:String, tank:int, mpg:double) + getModel() : String + estimateDistance() : double

12/06/2014F21SF SEF L241 To Do Now Read over the lecture and look at the code. If you want to install java and eclipse on your own computer, do so. Or you can wait until after the first lab. Java SE JDK http://www.oracle.com/technetwork/java/javase/downl oads/index.html http://www.oracle.com/technetwork/java/javase/downl oads/index.html Eclipse IDE for Java Developers http://www.eclipse.org/downloads/ http://www.eclipse.org/downloads/ If youre already familiar with another IDE for running java programs, youre welcome to continue with it.

12/06/2014F21SF SEF L242 Try running the programs In the first lab or at home, follow the separate Lab 1 instruction handout, which gives you Experience with running a java program from the command line Experience with using an ide such as eclipse

Similar presentations