1、Chapter 3 Implementing Classes,Introduction,In the previous chapter, we saw how to use objects Declare an object Book aBook; Create an object aBook = new Book(“Beloved”,“Toni Morrison”); Call methods on an object aBook.getAuthor();,Introduction,Remember our goal is to write programs that accomplish
2、something useful How do objects fit in? Encapsulation EfficiencyWe can also make our own types of objects,Example Program,public class Example public static void main(String args)Path p = new Path(3,4);System.out.println(“The distance is ”+ p.calcDistance()+ “ miles and the”+ “ angle is ”+ p.calcAng
3、le(); ,Example Program,This is great, except there is no Path class in the Java API The program would be easy if we had that type of objectSo well just write a Path class ourselves,Black Boxes,What is a black box?Why do we call it a black box?What are some instances of a black box?,Black Boxes,A bla
4、ck box works magically we press a button and something happensWe dont know how it actually works Encapsulation: the hiding of unimportant details,Black Boxes,Not everything is hidden in a black box We can input some numbers There is some sort of outputThere are ways to interact with it, but its all
5、done on the outside Interaction possibilities are well defined,Encapsulation,What is the right concept for each particular black box? Concepts are discovered through abstraction Abstraction: taking away inessential features, until only the essence of the concept remains How much does a user really n
6、eed to know?,Example: Cars,Black boxes in a car: transmission, electronic control module, etc,Example: Car,Users of a car do not need to understand how black boxes work Interaction of a black box with outside world is well-defined Drivers interact with car using pedals, buttons, etc. Mechanic can te
7、st that engine control module sends the right firing signals to the spark plugs For engine control module manufacturers, transistors and capacitors are black boxes magically produced by an electronics component manufacturer,Example: Car,Encapsulation leads to efficiency: Mechanic deals only with car
8、 components (e.g. electronic control module), not with sensors and transistors Driver worries only about interaction with car (e.g. putting gas in the tank), not about motor or electronic control module,Example: Doorbell,What can we do to a doorbell?What output do we get from a doorbellDo we actuall
9、y know how a doorbell works?Do we need to?,Encapsulation,In Object-oriented programming (OOP) the black boxes we use in our programs are objects String is a black box Rectangle is a black box,Software Design,Encapsulation,Old times: computer programs only manipulated primitive types such as numbers
10、and characters Gradually programs became more complex, vastly increasing the amount of detail a programmer had to remember and maintain,Encapsulation,Solution: Encapsulate routine computations to software black boxes Abstraction used to invent higher-level data types In object-oriented programming,
11、objects are black boxes,Encapsulation,Encapsulation: Programmer using an object knows about its behavior, but not about its internal structure In software design, you can design good and bad abstractions / objects; understanding what makes good design is an important part of the education of a softw
12、are engineer,Abstraction,Who designs objects you use? Other programmersWhat do these objects contain? Other objects Lesson: Multiple levels of abstraction Almost always, you will be designing an abstraction while simultaneously using another one,Review,Until now, youve only used objects Analogous to
13、 engineer who puts final parts together in carNow you will learn how to design objects Analogous to designing the parts of the carThis is a complex process,Designing a Class,Recall that a class is a template for objects Its the cookie cutter, not the cookiesYou need to decide: What does the black bo
14、x need to do? (methods) What does the black box need to know? (data),Designing a Class,Remember: you are designing a class that another programmer could use. Make it easy to understand Design your class as a black box,Methods,The first thing a class requires is a list of methods what should the blac
15、k box do? For our Path example: calcDistance calcAngle setX setY getX getY Which methods are accessors and which are mutators?,Methods,access specifier (eg public) return type (eg String or void) method name (eg deposit) list of parameters (eg New value for x) method body in braces ,Methods,Examples
16、: public double calcDistance() . public int getX() . public void setY(int newY) .,Methods: Syntax,accessSpecifier returnType methodName(parameterType parameterName,.) method body Example:public double calcDistance() . . . Purpose: To define the behavior of a method,Methods,Notes: Methods always have
17、 parentheses The return type is what type of output the black box will give the user Parameters are what types of input the user needs to provide The method body is a sequence of instructions,Constructors,Recall that we need to be able to create objects in order to use them The set of instructions t
18、hat does is this a constructor Note: Constructor name = Class namepublic Path() / body-filled in later ,Constructors,Constructor body is executed when a new object is created Statements in constructor body will set up the object so it can be used A constructor initializes all data members How does t
19、he compiler know which constructor to call?,Constructors vs. Methods,Constructors are a specialization of methods Goal: to set the internal data of the object to a valid state 2 major differences All constructors are named after the class Therefore all constructors of a class have the same name No r
20、eturn type is EVER listed!,Constructors: Syntax,accessSpecifier ClassName(parameterType parameterName, . . .) constructor body Example: public Path(int x, int y) . . . Purpose: To define the behavior of a constructor,Public Interface,The public constructors and methods of a class form the public int
21、erface of the class.public class Path / data fields-filled in later / Constructors public Path() / body-filled in later ,public Path(int initX, int initY) / body-filled in later / Methods public double calcDistance() / body-filled in laterpublic int getX() / body-filled in later public void setY() /
22、 body-filled in later / more methods ,Class Definition Syntax,accessSpecifier class ClassName fields constructorsmethods Example: public class Path public Path(int initY, int initY) . public double calcDistance() . . . . Purpose:To define a class, its public interface, and its implementation details
23、,Review,Public methods and constructors provide the public interface to a class They are how you interact with the black boxOur class is simple, but we can do many things with it Notice we havent defined the method body yet, but know how we can use it,Javadoc Comments,Part of creating a well-defined
24、 public interface is always commenting the class and method behaviorsThe HTML pages from the API are created from special comments in your program called javadoc commentsPlaced before the class or method /*/,Javadoc Comments,Begin with /* Ends with */ Put * on lines in between as convention, makes i
25、t easier to read Javadoc tags - indicates a tag author, param, return Benefits Online documentation Other java documents,Javadoc Comments,First part is a description of the method Carefully explain methodparam for each parameter Omit if no parametersreturn for the value returned Omit if return type
26、void,/* Calculates line of sight distance* return the calculated distance*/public double calcDistance() / implementation filled in later /* Changes the vertical distance* param newY the new distance in the y* direction*/ public void setY(int newY) / implementation filled in later ,Javadoc Comments,A
27、 class comment succinctly describes the class /* A path has a vertical distance and horizontal distance and users can determine diagonal distance and angles using this classauthor David Koop (dakoop) */ public class Path . . . ,Commenting,Seems repetitive, but is necessary Very helpful if you commen
28、t before you code your methodsProvide documentation comments for every class every method every parameter every return value. When in doubt, comment But make sure comments are concise,Instance Fields,Remember: methods and constructors comprise the public interface of a classInstance Fields are part
29、of the internal workings - An object stores its data in instance fields Field: a technical term for a storage location inside a block of memory Instance of a class: an object of the class AKA Data Members,Instance Fields,The class declaration specifies the instance fields: public class Path private
30、int xDistance;private int yDistance; .,Instance Fields,An instance field declaration consists of the following parts: access specifier (usually private) type of variable (eg double) name of variable (eg xDirection) Each object of a class has its own set of instance fields You should declare all inst
31、ance fields as private,Access Specifiers,Access Specifier defines the accessibility of the instance field and methods private only accessible within methods defined in the class public accessible both within methods defined in the class and in other classesprivate enforces encapsulation/black boxAKA
32、 Visibility Modifier,Instance Fields,accessSpecifier class ClassName . . .accessSpecifier fieldType fieldName; . . . Example:public class Path . . . private int xDistance; . . . Purpose: To define a field that is present in every object of a class,Accessing Instance Fields,The setX method of the Pat
33、h class can access the private instance field xDistance:public void setX(int newX) xDistance = newX; ,Accessing Instance Fields,Other methods cannot access xDistance:public class ChangePath public static void main(String args) Path p = new Path(3,4);. . . p.xDistance = 12; / ERROR ,Instance Fields,E
34、ncapsulation = Hiding data and providing access through methods By making data members private, we hide internal workings of a class from a userNote: We can have public instance fields and private methods, but commonly we do not,Constructor Bodies,Constructors contain instructions to initialize the
35、instance fields of an object public Path() xDistance = 0;yDistance = 0; public Path(int initX, int initY) xDistance = initX;yDistance = initY; ,Constructors What Happens?,Path p = new Path(4,5); Create a new object of type Path Call the second version of the constructor (since parameters are supplie
36、d) Sets the parameters initX to 4 and initY to 5 Executes the list of instructions in the constructor body Return an object reference, that is, the memory location of the object, as the value of the new expression Store that object reference in the variable p,Method Bodies,Methods have several compo
37、nents that allow them to be functional units of code. Declaration (method signature) Method Body Makes use of parameters (inputs) May return a value (output) Sequence of instructions may call other methods, declare variables, create objects, print output, etc.,Method Bodies,Some methods do not retur
38、n a value public void setY(int newY) yDistance = newY; Some methods return an output value public int getX() return xDistance; ,Implementing Methods,public double calcDistance() double sumSquares = xDistance*xDistance +yDistance*yDistance;return Math.sqrt(sumSquares); ,Methods What Happens?,p.setY(8
39、7); Set the parameter variable newY to 500 Executes the list of instructions in the method body: Sets the instance field yDistance to value of newY p.getX(); No parameter values to set Executes the list of instructions in the method body Returns the value of expression after return statement,Return
40、Statement Syntax,return expression; or return;Example: return balance; Purpose: To specify the value that a method returns, and exit the method immediately. The return value becomes the value of the method call expression.,Methods,Why do we write methods? Why not just have one long list of instructi
41、ons in our programs?smaller easier test & debug once, execute as often as needed much more readable code,Three Types of Classes,This isnt in the book In this course, there are three types of classes you will write: A new encapsulation A tester class An application,Classes: Type 1,Source code that de
42、fines a new data type by encapsulating:data members constructors methodsEx. Path class we just created AKA Instantiable class designed so that we can make objects,/* Stores information about one pet. */ public class Pet /* Name of the pet. */private String name, kind;private int age;/* Initializes a
43、 new instance.* param n The pets name.*/public Pet( String n, String k, int a ) name = n; kind = k; age = a;/* Returns the name of this pet. */public String getName() return name; /* Changes the name of this pet.* param newName The new name of the pet.*/public void changeNameTo( String newName ) / T
44、EST THE NAME HEREname = newName; ,Data member,Constructor,Methods,Classes: Type 2,Code that is written to test another class.Has a main method that: Creates instances of the class Executes methods Compares the actual output with expected output Classes should be tested before being used in Java Appl
45、ications.,/* A Test Program. */ public class TestPet /* * Test Program starts here. * param args Unused in this program.*/public static void main( String args ) / Declare and create a petPet pet1 = new Pet( “George“, “bird“, 14 );/ Test the pets informationtestGetName( pet1, “George” );/* Tests Pet
46、getName method. */public static void testGetName( Pet pet,String expectedName ) System.out.println( pet.getName() +“ should be ” + expectedName ); ,Classes: Type 3,Java ApplicationSource code that uses instances of other classes (objects) to solve problems. Must have a main method.Ex. Programs you c
47、ompleted in A0,/* A Java Application. */ public class PetApplication /* * Program starts here. * param args Unused in this program.*/public static void main( String args ) / Declare and create a petPet pet1 = new Pet( “George“, “bird“, 14 );/ Output the pets informationdisplay( pet1 );/* Prints Pet
48、information to screen. */public static void display( Pet pet ) System.out.println(pet.getName() + “ is a “ +pet.getAge() + “ year old “ + pet.getKind() ); ,Testing Instantiable Classes,Weve seen how to design an instantiable class, but By itself, we cannot actually run an instantiable class It has n
49、o main() method, like most classes We create instances of it in other classesIdea: use a test class to make sure it works properly before letting people use our class,Testing Instantiable Classes,Test class: a class with a main method that contains statements to test another class. Typically carries out the following steps: Construct one or more objects of the class that is being tested Invoke one or more methods Print out one or more results Verify output is correct and the program behaves as expected,