430 likes | 569 Views
2 A first Object-oriented program. Dept of Computer Science. F21SF Software Engineering Foundations. Monica Farrow EM G30 email : M.Farrow@hw.ac.uk Material available on Vision. Topics. Developing a first object-oriented program, looking at Data types Instance variables
E N D
F21SF SEF L2 2 A first Object-oriented program Dept of Computer Science F21SFSoftware Engineering Foundations Monica Farrow EM G30 email : M.Farrow@hw.ac.uk Material available on Vision
F21SF SEF L2 Topics • Developing a first object-oriented program, looking at • Data types • Instance variables • Constructors • Methods • Arithmetic operators • UML class and sequence diagrams are introduced
F21SF SEF L2 A first object-oriented program We’d 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. We’d 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
F21SF SEF L2 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
F21SF SEF L2 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 We’ll keep reinforcing class design so that you absorb the ideas over time
F21SF SEF L2 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
F21SF SEF L2 Customer MainClass Customer Collection Process Transactions Account Collection Account 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
F21SF SEF L2 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 today’s 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
F21SF SEF L2 Car Responsibilities Maintain data about model, tank size and mgp Return model details Calculate and return the distance that the car can travel on a full tank 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)
F21SF SEF L2 MainClass Car Today’s 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 car’s data and display results • A Car class managing everything about cars. This is a typical class, although very small
F21SF SEF L2 Objects and classes We’d 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
F21SF SEF L2 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
F21SF SEF L2 Outline UML Class diagram MainCar main(..) Car model tank size manufacturer’s mpg create car with initial data return the model return the estimated distance data operations (doing things with the data)
F21SF SEF L2 Outline UML sequence diagram objects Standard output main() Create a car myCar:Car methods of a class Get the model of the car the long rectangle represents the main method Get the distance Use standard output to display results calling the methods (vertical order is important)
F21SF SEF L2 Class outline public class Classname { //instance variables //constructor(s) //methods } So a Car class starts public class Car
F21SF SEF L2 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 can’t 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.
F21SF SEF L2 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/nutsandbolts/datatypes.html for more details • 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
F21SF SEF L2 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;
F21SF SEF L2 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
F21SF SEF L2 Creating an object We will create objects today in the main method, using a statement that looks like this: Data type Assign RHS value to LHS variable Car myCar = new Car (“Ford Ka”, 40, 33.6); Variable name Provide the data values as parameters Create a new object Call the Car constructor
F21SF SEF L2 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: Class name, starts upper case public Car (String model, int tank, double mpg) Means that any other class can use the constructor Type and name used for parameters
F21SF SEF L2 Car class - constructor The constructor’s 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; }
F21SF SEF L2 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 Instance variable tankSize = tank parameter Instance variable this.model = model parameter
F21SF SEF L2 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
F21SF SEF L2 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; } }
F21SF SEF L2 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 isn’t one!
F21SF SEF L2 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
F21SF SEF L2 main() myCar:Car new Car(“Ka”,40,7.4) 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.
F21SF SEF L2 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 tankwe 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
F21SF SEF L2 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");
F21SF SEF L2 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
F21SF SEF L2 The getModel method in the Car class Access modifier Return type method name, starts lowercase Any parameters in brackets (none) public String getModel() { return model; } Return statement One of the instance variables Curly brackets enclose method body
F21SF SEF L2 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; }
F21SF SEF L2 ARITHMETIC OPERATORS Operators are: +: addition, -: subtraction, *: multiplication, /: division (different effect for integers/reals) %: remainder (only for integers, also called mod) ++, +=: incrementation operators --, -=: decrementation operators
F21SF SEF L2 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
F21SF SEF L2 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.
F21SF SEF L2 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
F21SF SEF L2 A more detailed Sequence diagram Standard output main() new Car(“Ka”,40,7.4) myCar:Car model = getModel() distance= estimateDistance() println(message incl model & distance)
F21SF SEF L2 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
F21SF SEF L2 Class diagram MainCar main(..) Car - model : String - tankSize : int - manfMPL : double + Car(model:String, tank:int, mpg:double) + getModel() : String + estimateDistance() : double
F21SF SEF L2 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 JDKhttp://www.oracle.com/technetwork/java/javase/downloads/index.html • Eclipse IDE for Java Developershttp://www.eclipse.org/downloads/ • If you’re already familiar with another IDE for running java programs, you’re welcome to continue with it.
F21SF SEF L2 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