A First Look At Classes Chapter 6. Procedural Programming In procedural- programming all the program...

81
A First Look At Classes Chapter 6

Transcript of A First Look At Classes Chapter 6. Procedural Programming In procedural- programming all the program...

Slide 1

A First Look At ClassesChapter 6Procedural ProgrammingIn procedural- programming all the program functionality is written in a few modules of code or maybe one module (depending on the program). These modules depend on one another and sometimes changing a line of code requires you to rewrite the whole module again and maybe the whole program.

In Object-Oriented Programming programmers write independent parts of a program called classes. Each class represents a part of the program functionality and these classes can be assembled to form a program. When you need to change some of the program functionality all you have to do is to replace the target class which may contain the problem that needs changeObject-Oriented ProgrammingThe Worlds objects and classesIn our world we have classes and objects for those classes. Everything in our world is considered to be an object. For example, people are objects, animals are objects too, minerals are objects; everything in the world is an object. Easy, right? But what about classes? In our world we have to differentiate between objects that we are living with. So we must understand that there are classifications (this is how they get the name and the concepts of the Class) for all of those objects. For example, I'm an object, David is object too, Maria is another object. So we are from a people class (or type). I have a dog called Rover so it's an object. My friend's dog, Ntombomsi, is also an object so they are from a Dogs class (or type). The Worlds objects and classesIn our world we have classifications for objects and every object must be from some classification. So, a Class is a way for describing some properties and functionalities or behaviors of a group of objects. In other words, the class is considered to be a template for some objects. So maybe we will create a class called person which is a template of the functionality and the properties of persons.The Worlds objects and classesProgrammers objects and classesThe class: A building block that contains the properties and functionalities that describe some group of objects. We can create a class Person that contains:

Programmers objects and classesThe properties of any normal person on the earth like: hair color, age, height, weight, eye color.

Programmers objects and classesThe properties of any normal person on the earth like: hair color, age, height, weight, eye color.

Programmers objects and classesThe properties of any normal person on the earth like: hair color, age, height, weight, eye color.

Programmers objects and classesThe properties of any normal person on the earth like: hair color, age, height, weight, eye color.

Programmers objects and classesThe properties of any normal person on the earth like: hair color, age, height, weight, eye color.

Programmers objects and classesThe functionalities or behaviors of any normal person on the earth like: drink water, eat, go to the work.

Programmers objects and classesThe functionalities or behaviors of any normal person on the earth like: drink water, eat, go to the work.

Programmers objects and classesThe functionalities or behaviors of any normal person on the earth like: drink water, eat, go to the work.

Programmers objects and classesThe functionalities or behaviors of any normal person on the earth like: drink water, eat, go to work.

When you create an object you can specify the properties of that object. One object can have different properties (hair color, age, height, weight) than another object. For example, I have brown eyes and you have green eyes. When I create 2 objects I will specify a brown color for my object's eye color property and I will specify a green color for your object's eye color property.Programmers objects and classesVariables declared in a class store the data for each instance. What does this mean? It means that when you instantiate this class (that is, when you create an object of this class) the object will allocate memory locations to store the data of its variables.

Programmers objects and classesThis is our simple class which contains 2 variables (fields):

public class Person{private int age;private String hairColor;}Programmers objects and classes6-20Access SpecifiersAn access specifier is a Java keyword that indicates how a field or method can be accessed.publicWhen the public access specifier is applied to a class member, the member can be accessed by code inside the class or outside.privateWhen the private access specifier is applied to a class member, the member cannot be accessed by code outside the class. The member can be accessed only by methods that are members of the same class.20It is a common practice to make all of a classs fields private and to provide public methods for accessing and changing those fields.

Programmers objects and classesA method that gets a value from a classs field but does not change it is known as an accessor method (getter).

public int getAge(){return age;}Programmers objects and classesA method that stores a value in a field or changes the value in a field in some other way is known as a mutator method (setter).

public void setAge(int Age){age = Age;}Programmers objects and classespublic class Person{private int age;private String hairColor;

public void setAge(int Age) { age = Age; }

public void setHairColor(String colorHair) { hairColor = colorHair; }

public int getAge() { return age; }

public String getHairColor() { return hairColor; }}private fields of the class Personpublic class Person{private int age;private String hairColor;

public void setAge(int Age) { age = Age; }

public void setHairColor(String colorHair) { hairColor = colorHair; }

public int getAge() { return age; }

public String getHairColor() { return hairColor; }}Access specifierReturn TypeMethod NameNotice the word static does not appear in the method header designed to work on an instance of a class (instance method).Parameter variable declarationpublic class Person{private int age;private String hairColor;

public void setAge(int Age) { age = Age; }

public void setHairColor(String colorHair) { hairColor = colorHair; }

public int getAge() { return age; }

public String getHairColor() { return hairColor; }}MutatorsAccessorspublic class Person{private int age;private String hairColor;

public void setAge(int Age)Person jake = new Person(); {jake.setAge(10); age = Age; }

public void setHairColor(String colorHair) { hairColor = colorHair; }

public int getAge() { return age; }

public String getHairColor() { return hairColor; }}public class Person{private int age;private String hairColor;

public void setAge(int Age)Person jake = new Person(); {jake.setAge(10); age = Age; }

public void setHairColor(String colorHair)jake.setHairColor(Brown); { hairColor = colorHair; }

public int getAge() { return age; }

public String getHairColor() { return hairColor; }}public class Person{private int age;private String hairColor;

public void setAge(int Age)Person jake = new Person(); {jake.setAge(10); age = Age; }

public void setHairColor(String colorHair)jake.setHairColor(Brown); { hairColor = colorHair; }

public int getAge()jake.getAge(); { return age; }

public String getHairColor() { return hairColor; }}public class Person{private int age;private String hairColor;

public void setAge(int Age)Person jake = new Person(); {jake.setAge(10); age = Age; }

public void setHairColor(String colorHair)jake.setHairColor(Brown); { hairColor = colorHair; }

public int getAge()jake.getAge(); { return age; }

public String getHairColor()jake.getHairColor(); { return hairColor; }}public static void main(String[] args){ Person jake = new Person(); Person david = new Person(); jake.setAge(20); jake.setHairColor("Brown"); david.setAge(30); david.setHairColor("Blonde"); System.out.println("Jake's age is " + jake.getAge() + " and his hair color is " + jake.getHairColor()); System.out.println("David's age is " + david.getAge() + " and his hair color is " + david.getHairColor());

}

6-32Building a Rectangle classA Rectangle object will have the following fields:length. The length field will hold the rectangles length.width. The width field will hold the rectangles width.326-33Building a Rectangle classThe Rectangle class will also have the following methods:setLength. The setLength method will store a value in an objects length field.setWidth. The setWidth method will store a value in an objects width field.getLength. The getLength method will return the value in an objects length field.getWidth. The getWidth method will return the value in an objects width field.getArea. The getArea method will return the area of the rectangle, which is the result of the objects length multiplied by its width.336-34UML DiagramUnified Modeling Language (UML) provides a set of standard diagrams for graphically depicting object-oriented systems.Class name goes hereFields are listed hereMethods are listed here346-35UML Diagram for Rectangle classRectanglelengthwidthsetLength() setWidth() getLength() getWidth() getArea()356-36Writing the Code for the Class Fieldspublic class Rectangle{private double length;private double width;}

366-37public class Rectangle{ private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w) { width = w; } public double getLength() { return length; } public double getWidth() { return width; } public double getArea() { return length * width; }}

376-38public class Rectangle{ private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w)box.setWidth(10.0); { width = w; } public double getLength() { return length; } public double getWidth() { return width; } public double getArea() { return length * width; }}

386-39public class Rectangle{ private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w)box.setWidth(10.0); { width = w; } public double getLength()box.getLength(); { return length; } public double getWidth() { return width; } public double getArea() { return length * width; }}

396-40public class Rectangle{ private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w)box.setWidth(10.0); { width = w; } public double getLength()box.getLength(); { return length; } public double getWidth()box.getWidth(); { return width; } public double getArea() { return length * width; }}

406-41public class Rectangle{ private double length; private double width; public void setLength(double len)Rectangle box = new Rectangle(); {box.setLength(12.0); length = len; } public void setWidth(double w)box.setWidth(10.0); { width = w; } public double getLength()box.getLength(); { return length; } public double getWidth()box.getWidth(); { return width; } public double getArea() box.getArea(); { return length * width; }}

416-42public class RectangleDemo{ public static void main(String[] args) { // Create a Rectangle object. Rectangle box = new Rectangle();

// Set length to 10.0 and width to 20.0. box.setLength(10.0); box.setWidth(20.0);

// Display the length. System.out.println("The box's length is " + box.getLength());

// Display the width. System.out.println("The box's width is " + box.getWidth());

// Display the area. System.out.println("The box's area is " + box.getArea()); }

}

426-43Creating a Rectangle objectRectangle box = new Rectangle ();address0.00.0length:width:The box variable holds the address of the Rectangle object.A Rectangle object436-44Calling the setLength Methodbox.setLength(10.0);address10.00.0length:width:The box variable holds the address of the Rectangle object.A Rectangle objectThis is the state of the box object after the setLength method executes.446-45Accessor and Mutator MethodsBecause of the concept of data hiding, fields in a class are private.The methods that retrieve the data of fields are called accessors.The methods that modify the data of fields are called mutators.Each field that the programmer wishes to be viewed by other classes needs an accessor.Each field that the programmer wishes to be modified by other classes needs a mutator.456-46Accessors and MutatorsFor the Rectangle example, the accessors and mutators are:setLength: Sets the value of the length field.public void setLength(double len) setWidth: Sets the value of the width field.public void setLength(double w) getLength: Returns the value of the length field.public double getLength() getWidth: Returns the value of the width field.public double getWidth() Other names for these methods are getters and setters.466-47Stale DataSome data is the result of a calculation.Consider the area of a rectangle.length widthIt would be impractical to use an area variable here.Data that requires the calculation of various factors has the potential to become stale.To avoid stale data, it is best to calculate the value of that data within a method rather than store it in a variable.476-48Stale DataRather than use an area variable in a Rectangle class:public double getArea(){return length * width;}This dynamically calculates the value of the rectangles area when the method is called.Now, any change to the length or width variables will not leave the area of the rectangle stale.486-49UML Data Type and Parameter NotationRectangle- width : double+ setWidth(w : double) : voidAccess modifiers are denoted as:+public-privateUML diagrams are language independent.UML diagrams use an independent notation to show return types, access modifiers, etc.6-50UML Data Type and Parameter NotationRectangle- width : double+ setWidth(w : double) : voidVariable types are placed after the variable name, separated by a colon.UML diagrams are language independent.UML diagrams use an independent notation to show return types, access modifiers, etc.6-51UML Data Type and Parameter NotationRectangle- width : double+ setWidth(w : double) : voidMethod return types are placed after the method declaration name, separated by a colon.UML diagrams are language independent.UML diagrams use an independent notation to show return types, access modifiers, etc.6-52UML Data Type and Parameter NotationRectangle- width : double+ setWidth(w : double) : voidMethod parameters are shown inside the parentheses using the same notation as variables.UML diagrams are language independent.UML diagrams use an independent notation to show return types, access modifiers, etc.6-53Converting the UML Diagram to CodePutting all of this information together, a Java class file can be built easily using the UML diagram.The UML diagram parts match the Java class file structure.ClassNameFieldsMethodsclass header{FieldsMethods}6-54Converting the UML Diagram to CodeRectangle width : double length : double+ setWidth(w : double) : void+ setLength(len : double): void+ getWidth() : double+ getLength() : double+ getArea() : doublepublic class Rectangle{private double width;private double length;

public void setWidth(double w){}public void setLength(double len){}public double getWidth(){return 0.0;}public double getLength(){return 0.0;}public double getArea(){return 0.0;}}

The structure of the class can be compiled and tested without having bodies for the methods. Just be sure to put in dummy return values for methods that have a return type other than void.6-55Converting the UML Diagram to Codepublic class Rectangle{private double width;private double length;

public void setWidth(double w){width = w;}public void setLength(double len){length = len;}public double getWidth(){return width;}public double getLength(){return length;}public double getArea(){return length * width;}}

Rectangle width : double length : double+ setWidth(w : double) : void+ setLength(len : double): void+ getWidth() : double+ getLength() : double+ getArea() : doubleOnce the class structure has been tested, the method bodies can be written and tested. 6-56Class Layout ConventionsThe layout of a source code file can vary by employer or instructor.A common layout is:Fields listed firstMethods listed secondAccessors and mutators are typically grouped.There are tools that can help in formatting layout to specific standards.566-57Instance Fields and MethodsFields and methods that are declared as previously shown are called instance fields and instance methods.Objects created from a class each have their own copy of instance fields.Instance methods are methods that are not declared with a special keyword, static.576-58Instance Fields and MethodsInstance fields and instance methods require an object to be created in order to be used.See example: RoomAreas.javaNote that each room represented in this example can have different dimensions.Rectangle kitchen = new Rectangle();Rectangle bedroom = new Rectangle();Rectangle den = new Rectangle();586-59States of Three Different Rectangle Objectsaddress15.012.0length:width:address10.014.0length:width:address20.030.0length:width:The kitchen variable holds the address of a Rectangle Object.The bedroom variable holds the address of a Rectangle Object.The den variable holds the address of a Rectangle Object.596-60ConstructorsClasses can have special methods called constructors.A constructor is a method that is automatically called when an object is created.Constructors are used to perform operations at the time an object is created.Constructors typically initialize instance fields and perform other object initialization tasks.606-61ConstructorsConstructors have a few special properties that set them apart from normal methods.Constructors have the same name as the class.Constructors have no return type (not even void).Constructors may not return any values.Constructors are typically public.616-62Constructor for Rectangle Classprivate double length;private double width;

public Rectangle(double len, double w) { length = len; width = w; }

Call: Rectangle box = new Rectangle(5.0,15.0);626-63Constructors in UMLIn UML, the most common way constructors are defined is:Rectangle width : double length : double+Rectangle(len:double, w:double)+ setWidth(w : double) : void+ setLength(len : double): void+ getWidth() : double+ getLength() : double+ getArea() : doubleNotice there is noreturn type listedfor constructors.6-64Uninitialized Local Reference VariablesReference variables can be declared without being initialized.Rectangle box;This statement does not create a Rectangle object, so it is an uninitialized local reference variable.A local reference variable must reference an object before it can be used, otherwise a compiler error will occur. box = new Rectangle(7.0, 14.0);box will now reference a Rectangle object of length 7.0 and width 14.0.646-65The Default ConstructorWhen an object is created, its constructor is always called.If you do not write a constructor, Java provides one when the class is compiled. The constructor that Java provides is known as the default constructor.It sets all of the objects numeric fields to 0.It sets all of the objects boolean fields to false.It sets all of the objects reference variables to the special value null.656-66The Default ConstructorThe default constructor is a constructor with no parameters, used to initialize an object in a default configuration.The only time that Java provides a default constructor is when you do not write any constructor for a class.A default constructor is not provided by Java if a constructor is already written.666-67Writing Your Own No-Arg ConstructorA constructor that does not accept arguments is known as a no-arg constructor. The default constructor (provided by Java) is a no-arg constructor.We can write our own no-arg constructor

public Rectangle(){length = 1.0;width = 1.0;}676-68The String Class ConstructorOne of the String class constructors accepts a string literal as an argument.This string literal is used to initialize a String object.For instance:

String name = new String("Michael Long");686-69The String Class ConstructorThis creates a new reference variable name that points to a String object that represents the name Michael LongBecause they are used so often, String objects can be created with a shorthand:

String name = "Michael Long";696-70Overloading Methods and ConstructorsTwo or more methods in a class may have the same name as long as their parameter lists are different. When this occurs, it is called method overloading. This also applies to constructors.Method overloading is important because sometimes you need several different ways to perform the same operation.706-71Overloaded Method addpublic int add(int num1, int num2){int sum = num1 + num2;return sum;}

public String add (String str1, String str2){String combined = str1 + str2;return combined;}716-72Method Signature and BindingA method signature consists of the methods name and the data types of the methods parameters, in the order that they appear. The return type is not part of the signature.

add(int, int)add(String, String)

The process of matching a method call with the correct method is known as binding. The compiler uses the method signature to determine which version of the overloaded method to bind the call to.Signatures of the add methods of previous slide726-73Rectangle Class Constructor OverloadIf we were to add the no-arg constructor we wrote previously to our Rectangle class in addition to the original constructor we wrote, what would happen when we execute the following calls?

Rectangle box1 = new Rectangle();Rectangle box2 = new Rectangle(5.0, 10.0);

736-74Rectangle Class Constructor OverloadIf we were to add the no-arg constructor we wrote previously to our Rectangle class in addition to the original constructor we wrote, what would happen when we execute the following calls?

Rectangle box1 = new Rectangle();Rectangle box2 = new Rectangle(5.0, 10.0);

The first call would use the no-arg constructor and box1 would have a length of 1.0 and width of 1.0.The second call would use the original constructor and box2 would have a length of 5.0 and a width of 10.0.

746-75The BankAccount ExampleBankAccount.java AccountTest.javaBankAccount-balance:double+BankAccount()+BankAccount(startBalance:double)+BankAccount(str:String)+deposit(amount:double):void+deposit(str:String):void+withdraw(amount:double):void+withdraw(str:String):void+setBalance(b:double):void+setBalance(str:String):void+getBalance():doubleOverloaded ConstructorsOverloaded deposit methodsOverloaded withdraw methodsOverloaded setBalance methods756-76Scope of Instance FieldsVariables declared as instance fields in a class can be accessed by any instance method in the same class as the field.If an instance field is declared with the public access specifier, it can also be accessed by code outside the class, as long as an instance of the class exists.766-77ShadowingA parameter variable is, in effect, a local variable.Within a method, variable names must be unique.A method may have a local variable with the same name as an instance field.This is called shadowing.The local variable will hide the value of the instance field.Shadowing is discouraged and local variable names should not be the same as instance field names.public void setLength(double len){int length;length = len;;}776-78Packages and import StatementsClasses in the Java API are organized into packages.Explicit and Wildcard import statementsExplicit imports name a specific classimport java.util.Scanner;Wildcard imports name a package, followed by an *import java.util.*;

The java.lang package is automatically made available to any Java class.786-79Some Java Standard Packages

796-80Object Oriented DesignFinding Classes and Their ResponsibilitiesFinding the classesGet written description of the problem domainIdentify all nouns, each is a potential classRefine list to include only classes relevant to the problem

Identify the responsibilitiesThings a class is responsible for knowingThings a class is responsible for doingRefine list to include only classes relevant to the problem

806-81Object Oriented DesignFinding Classes and Their ResponsibilitiesIdentify the responsibilitiesThings a class is responsible for knowingThings a class is responsible for doingRefine list to include only classes relevant to the problem

81