©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes
OOP Object-Oriented programs are organized around data rather than procedures A program is a model of the world –objects represent things in the real world
Example: TV Think about your television as an object. You send messages to it using the remote control. What messages can you send? What data is needed to represent the state of the TV?
What other kinds of objects can you think of? –What properties do they have? (What data is needed to represent them?) –What kinds of messages to they respond to?
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Object-Oriented Terms Abstraction - high-level view Interface - protocol for communication Encapsulation - objects are self-contained Information hiding - protect object data Generality - use class for related tasks Extensibility - add capabilities through inheritance
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Why Define Your Own Classes? Standard classes do not meet all of our needs. Classes need to be customized to applications. Classes are used to build large programs.
Two Extremes Static classes Only class data and methods You don't create instances (use new) Examples –Math –JOptionPane Driver classes –Examples from Chapter 3 Instantiable classes Used for defining objects Each object has its own data –methods have access to object's data Examples –DecimalFormat –Date, DateFormat
Template for Driver Class
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter main Method Template public static void main( String[ ] args ){ JFramemyWindow; myWindow = new JFrame( ); myWindow.setSize(300, 200); myWindow.setTitle(“My First Java Program”); myWindow.setVisible(true); } Method Body Modifier Return Type Method Name Parameter
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Generic Class Method Template public static ( ){ /* code for what method does */ return ; } Method Body Modifier Return Type Method Name Parameters
Parameter Lists Describe the data method needs Empty if the method doesn't need data public static double random() { /* … */ } Need type and variable name for each public static double sqrt( double x) { /*…*/ } Separate multiple parameters with commas public static double pow( double a, double b) { /* … */ }
Return Types Specifies the type of information returned by the method –can be any Java type - a primitive type or a class name A method can only return one value or object –last statement needs to return something with the appropriate type void means the method doesn't return anything –void method does not need a return statement
Example method Calculating x coordinate from polar coordinates public static double xCoordinate( double rValue, double thetaR) { return rValue * Math.cos( thetaR); } Calling (using) the method from the same class double x = xCoordinate( r, thetaRad); Calling the method from another class double x = Polar.xCoordinate( r, thetaRad);
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Designing an Instantiable Class What role does the class play in the program? –What data does it need? –What behavior is required? –What can other classes do with it? –What information does it keep to itself? –How do we want to create the object?
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Instantiable Class: Student For a program to keep track of the courses a student has taken Data –name of student (first, middle and last names) –credits taken Create a student with name data Behavior –add a course –get the student's full name –compute the student's GPA
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter UML Class Diagram A box with three sections –Class name –Data members –Methods
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Template for Class Definition
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Data Members Data members (instance variables) –variables that are declared in the class body –store the data needed to describe a particular object –Instance variables are usually private Class data also declared in the body of the class –reserved word static indicates class data –constants are usually static use the modifier final to declare a constant
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Syntax for Data Member Declaration ; private String nameFirst ; Modifiers Data Type Name Any declaration needs a name and a type –Usually use private modifier for data member This allows the object to control its own data
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Instance Methods Define the behavior of an object –Instance methods use the object's data –Qualify instance methods with the name of an object –Methods can be either public or private interface to the other classes defined by public methods Class methods are independent of any particular object –Qualify class methods with the name of the class –Access to instance data only through an object
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Template for Instance Method ( ){ } public void addGrade (int credits, double grade) { creditsAttempted = creditsAttempted + credits; accumulatedPoints = accumulatedPoints + grade; } Statements Modifier Return Type Method Name Parameters
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Parameters Parameters describe the information needed by the method –parameter is a placeholder for the information needed by the method The parameter list consists of zero or more parameter declarations –parameters are separated by commas –parameter declaration is a type followed by a name
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Calling a method with Parameters When calling a method, provide a "value" for each parameter –An argument is a value we pass to a method. public class Account {... public void add(double amt) { balance = balance + amt; }... } public class Sample { public static void main(String[] arg) { Account acct = new Account();... acct.add(400);... }... } argument parameter
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Calling Methods same number of arguments as parameters match arguments and parameters by position types must be assignment- compatible
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Creating Objects Use new to instantiate (create) an object Student stu = new Student( "John", "Doe"); Student() is a constructor –a special method used to create a new instance Every class has at least one constructor –default constructor has no parameters Constructor with parameters initializes data with user- supplied values
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Constructor Template public ( ){ } public Student( String first, String last ) { nameFirst = first; nameLast = last; } Modifier Class Name Parameters Note: no return type
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Visibility Modifiers The modifiers public and private designate the visibility of data members and methods. –private members not accessible to client classes –public members can be used by client classes Information hiding : internal details of class hidden from clients.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Accessibility Example ClientService … Service obj = new Service(); obj.memberOne = 10; obj.memberTwo = 20; obj.doOne(); obj.doTwo(); … public class Service { public int memberOne; private int memberTwo; public void doOne() { … } private void doTwo() { … }
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Guideline for Visibility Modifiers Instance variables should be private. Methods are public if they are intended for use by client classes. Methods are private if used only by the other methods in the same class. Make class constants public to make them readable by the client programs.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter UML Notation for Visibility public – plus symbol (+) private – minus symbol (-)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Types of variables An identifier appearing inside a method can be a local variable, a parameter, or a data member. Search order –local variable declaration or a parameter –data member declaration –no matching declaration causes an error
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Local Variables Declared in body of method –used for storing intermediate results –not available outside method –parameters also local to the method
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Sample Matching
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Calling Methods of the Same Class When calling a method of another class –need to say what object/class it belongs to When calling a method from another method in the same class. –refer to a method with just its name
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Passing Objects to a Method Method parameters can be objects or primitive values A primitive value passed to a method is passed by value –value is copied into corresponding parameter variable For an object, we pass the reference (location) of the object by value –objects are not copied –the method has access to the original object
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Passing a Student Object
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Sharing an Object Can pass the same Student object to card1 and card2 The owner member of both LibraryCard objects refers to the same Student object
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Using a class We can create multiple Bicycle instances in any other class. Bicycle bike1, bike2; bike1 = new Bicycle( ); bike1.setOwnerName("Adam Smith"); bike2 = new Bicycle( ); bike2.setOwnerName("Ben Jones");
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Using Bicycle BicycleRegistrationBicycle BicycleRegistration uses Bicycle –instances are created in the main method SecondMain uses two classes SecondMainBicycleAccount
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter High-Level Class Diagrams Large programs use many classes Librarian is a main class –main method creates Student and Library card objects LibraryCard has a Student Student has two Strings
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Object-Oriented Design Divide and Conquer is one approach to solving large problems –Break the problem up into smaller tasks –Keep sub-dividing until each task becomes small enough to handle In object-oriented design, identify the objects in the problem –Look for nouns in the problem description –For each object identify data needed to describe the object operations needed to allow the object to do its job