Chapter 3 OOP main concepts PDF
Document Details
Uploaded by FamousDeStijl3725
KFU
Tags
Summary
This document is an introduction to Object-Oriented Programming (OOP) concepts, specifically focusing on the core building blocks of objects, classes, methods, states, and behaviors. It also covers the importance of program reuse. The document is a part of a larger programming course.
Full Transcript
Chapter 3 OOP main concepts Objects vs Classes. Identifying Objects. Distinguishing state and behavior ©1992-2012 by Pearson Education, Inc. All Rights Reserved. In Chapter 2, we have learned: To use different input statements Basic memory concepts (var...
Chapter 3 OOP main concepts Objects vs Classes. Identifying Objects. Distinguishing state and behavior ©1992-2012 by Pearson Education, Inc. All Rights Reserved. In Chapter 2, we have learned: To use different input statements Basic memory concepts (variables) To use arithmetic operators To use compound assignment operator To use Increment and Decrement Identify Java’s primitive data type Logical Operators Selection Statements (if, if.. Else, swich) Repetition Statements (for, while, do.. While, break, continue) © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. In Chapter 3, you will learn: How to declare a class and use it to create an object. How to implement a class’s behaviors as methods. How to implement a class’s attributes as instance variables and properties. How to call an object’s methods to make them perform their tasks. What instance variables of class and local variables of a method are. How to use constructor to initialize an object’s data How to use set method to initialize an object’s data, and how to use get methods to get object’s data. The differences between primitive and reference types. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Chapter 3 Content: Introduction Declaring a Class with Methods and Instantiating an Object of Class Declaring a method with Parameter Instance Variables. set Methods and get Methods Initializing Objects with Constructors © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Introduction Covered in this chapter Objects Classes Instance Methods Parameters double primitive type © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Graphical example on oop tech. CLASS State/ Behaviors Attribute /Methods..... Object 1 Object 3 Object 2 Introduction Object Car Bank Account Grade Book Class Design of Prius Account.java GradeBook.java Instance My Prius Account1 GB1 Property/ Engine, Balance, Interest, Course Name Field Color, etc etc Function/ Drive, Park, Withdraw, Calculate Method Brake,etc Check Balance average Deposit Paramete How hard you Amount to deposit Number of r press the brake students © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Introduction to Object Technology Objects, or more precisely, the classes objects come from, are essentially reusable software components. There are date objects, time objects, audio objects, video objects, automobile objects, people objects, etc. Almost any noun can be reasonably represented as a software object in terms of attributes (e.g., name, color and size) and behaviors (e.g., calculating, moving and communicating). Using a modular, object-oriented design and implementation approach can make software- development groups. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Introduction to Object Technology (Cont.) Recall The Automobile as an Object Let’s begin with a simple analogy. Suppose you want to drive a car and make it go faster by pressing its accelerator pedal. Before you can drive a car, someone has to design it. A car typically begins as engineering drawings, similar to the blueprints that describe the design of a house. Drawings include the design for an accelerator pedal. Pedal hides from the driver the complex mechanisms that actually make the car go faster, just as the brake pedal hides the mechanisms that slow the car, and the steering wheel “hides” the mechanisms that turn the car. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Introduction to Object Technology (Cont.) Enables people with little or no knowledge of how engines, braking and steering mechanisms work to drive a car easily. Before you can drive a car, it must be built from the engineering drawings that describe it. A completed car has an actual accelerator pedal to make the car go faster, but even that’s not enough—the car won’t accelerate on its own (hopefully!), so the driver must press the pedal to accelerate the car. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Introduction to Object Technology (Cont.) Methods and Classes Performing a task in a program requires a method. The method houses the program statements that actually perform its tasks. Hides these statements from its user, just as the accelerator pedal of a car hides from the driver the mechanisms of making the car go faster. In Java, we create a program unit called a class to house the set of methods that perform the class’s tasks. A class is similar in concept to a car’s engineering drawings, which house the design of an accelerator pedal, steering wheel, and so on. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Introduction to Object Technology (Cont.) Instantiation Just as someone has to build a car from its engineering drawings before you can actually drive a car, you must build an object of a class before a program can perform the tasks that the class’s methods define. An object is then referred to as an instance of its class. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Introduction to Object Technology (Cont.) Reuse Just as a car’s engineering drawings can be reused many times to build many cars, you can reuse a class many times to build many objects. Reuse of existing classes when building new classes and programs saves time and effort. Reuse also helps you build more reliable and effective systems, because existing classes and components often have gone through extensive testing, debugging and performance tuning. Just as the notion of interchangeable parts was crucial to the Industrial Revolution, reusable classes are crucial to the software revolution that has been spurred by object technology. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Introduction to Object Technology (Cont.) Messages and Methods Calls When you drive a car, pressing its gas pedal sends a message to the car to perform a task—that is, to go faster. Similarly, you send messages to an object. Each message is implemented as a method call that tells a method of the object to perform its task. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Introduction to Object Technology (Cont.) Attributes and Instance Variables A car has attributes Color, its number of doors, the amount of gas in its tank, its current speed and its record of total miles driven (i.e., its odometer reading). The car’s attributes are represented as part of its design in its engineering diagrams. Every car maintains its own attributes. Each car knows how much gas is in its own gas tank, but not how much is in the tanks of other cars. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Introduction to Object Technology (Cont.) An object, has attributes that it carries along as it’s used in a program. Specified as part of the object’s class. A bank account object has a balance attribute that represents the amount of money in the account. Each bank account object knows the balance in the account it represents, but not the balances of the other accounts in the bank. Attributes are specified by the class’s instance variables. ©1992-2012 by Pearson Education, Inc. All Rights Reserved. Graphical example on oop tech. CLASS State/ Behaviors Attribute /Methods..... Object 1 Object 3 Object 2 Declaring a Class with a Method and Instantiating an Object of a Class Create a new class (GradeBook) Use it to create an object. Each class declaration that begins with keyword public must be stored in a file that has the same name as the class and ends with the.java file-name extension. Keyword public is an access modifier. Indicates that the class is “available to the public” © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Declaring a Class with a Method and Instantiating an Object of a Class (Cont.) Method name follows the return type. By convention, method names begin with a lowercase first letter and subsequent words in the name begin with a capital letter. Empty parentheses after the method name indicate that the method does not require additional information to perform its task. Together, everything in the first line of the method is typically called the Method header Every method’s body is delimited by left and right braces. The method body contains one or more statements that perform the method’s task. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Declaring a Class with a Method and Instantiating an Object of a Class (Cont.) Use class GradeBook in an application. Class GradeBook is not an application because it does not contain main. Can’t execute GradeBook; will receive an error message like: Exception in thread "main" java.lang.NoSuchMethodError: main Must either declare a separate class that contains a main method or place a main method in class GradeBook. To help you prepare for the larger programs, use a separate class containing method main to test each new class. Some programmers refer to such a class as a driver class. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Declaring a Class with a Method and Instantiating an Object of a Class (Cont.) A static method (such as main) is special It can be called without first creating an object of the class in which the method is declared. Typically, you cannot call a method that belongs to another class until you create an object of that class. Declare a variable of the class type. Each new class you create becomes a new type that can be used to declare variables and create objects. You can declare new class types as needed; this is one reason why Java is known as an extensible language. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Declaring a Class with a Method and Instantiating an Object of a Class (Cont.) Class instance creation expression Keyword new creates a new object of the class specified to the right of the keyword. Used to initialize a variable of a class type. The parentheses to the right of the class name are required. Parentheses in combination with a class name represent a call to a constructor, which is similar to a method but is used only at the time an object is created to initialize the object’s data. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Declaring a Class with a Method and Instantiating an Object of a Class (Cont.) Call a method via the class-type variable Variable name followed by a dot separator (.), the method name and parentheses. Call causes the method to perform its task. Any class can contain a main method. The JVM invokes the main method only in the class used to execute the application. If multiple classes that contain main, then one that is invoked is the one in the class named in the java command. Compiling an Application with Multiple Classes Compile the classes in Fig. 3.1 and Fig. 3.2 before executing. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Declaring a Class with a Method and Instantiating an Object of a Class (Cont.) Type the command javac GradeBook.java GradeBookTest.java If the directory containing the application includes only this application’s files, you can compile all the classes in the directory with the command javac *.java © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. 3.3 Declaring a Class with a Method and Instantiating an Object of a Class (Cont.) Figure 3.3: UML class diagram for class GradeBook. Each class is modeled in a class diagram as a rectangle with three compartments. Top: contains the class name centered horizontally in boldface type. Middle: contains the class’s attributes, which correspond to instance variables (Section 3.5). Bottom: contains the class’s operations, which correspond to methods. Operations are modeled by listing the operation name preceded by an access modifier (in this case +) and followed by a set of parentheses. The plus sign (+) corresponds to the keyword public. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Declaring a Method with a Parameter Car analogy Pressing a car’s gas pedal sends a message to the car to perform a task—make the car go faster. The farther down you press the pedal, the faster the car accelerates. Message to the car includes the task to perform and additional information that helps the car perform the task. Parameter: Additional information a method needs to perform its task. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Declaring a Method with a Parameter (Cont.) A method can require one or more parameters that represent additional information it needs to perform its task. Defined in a comma-separated parameter list Located in the parentheses that follow the method name Each parameter must specify a type and an identifier. A method call supplies values—called arguments—for each of the method’s parameters. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Declaring a Method with a Parameter (Cont.) Scanner method nextLine Reads characters typed by the user until the newline character is encountered Returns a String containing the characters up to, but not including, the newline Press Enter to submit the string to the program. Pressing Enter inserts a newline character at the end of the characters the user typed. The newline character is discarded by nextLine. Scanner method next Reads individual words Reads characters until a white-space character is encountered, then returns a String (the white-space character is discarded). Information after the first white-space character can be read by other statements that call the Scanner’s methods later in the program-. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Declaring a Method with a Parameter (Cont.) More on Arguments and Parameters The number of arguments in a method call must match the number of parameters in the parameter list of the method’s declaration. The argument types in the method call must be “consistent with” the types of the corresponding parameters in the method’s declaration. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Graphical example on oop tech. CLASS State/ Behaviors Attribute /Methods..... Object 1 Object 3 Object 2 Instance Variables, set Methods and get Methods Local variables Variables declared in the body of a particular method. When a method terminates, the values of its local variables are lost. Recall from Section 3.2 that an object has attributes that are carried with the object as it’s used in a program. Such attributes exist before a method is called on an object and after the method completes execution. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Instance Variables, set Methods and get Methods (Cont.) A class normally consists of one or more methods that manipulate the attributes that belong to a particular object of the class. Attributes are represented as variables in a class declaration. Called fields. Declared inside a class declaration but outside the bodies of the class’s method declarations. Instance variable When each object of a class maintains its own copy of an attribute, the field is an instance variable Each object (instance) of the class has a separate instance of the variable in memory. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Instance Variables, set Methods and get Methods (Cont.) Every instance (i.e., object) of a class contains one copy of each instance variable. Instance variables typically declared private. private is an access modifier. private variables and methods are accessible only to methods of the class in which they are declared. Declaring instance private is known as data hiding or information hiding, more about it later in Encapsulation concept. private variables are encapsulated (hidden) in the object and can be accessed only by methods of the object’s class. Prevents instance variables from being modified accidentally by a class in another part of the program. Set and get methods used to access instance variables. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Instance Variables, set Methods and get Methods (Cont.) When a method that specifies a return type other than void completes its task, the method returns a result to its calling method. Method setCourseName and getCourseName each use variable courseName even though it was not declared in any of the methods. Can use an instance variable of the class in each of the classes methods. Exception to this is static methods (Chapter 8) The order in which methods are declared in a class does not determine when they are called at execution time. One method of a class can call another method of the same class by using just the method name. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Instance Variables, set Methods and get Methods (Cont.) Unlike local variables, which are not automatically initialized, every field has a default initial value—a value provided by Java when you do not specify the field’s initial value. Fields are not required to be explicitly initialized before they are used in a program—unless they must be initialized to values other than their default values. The default value for a field of type String is null © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Instance Variables, set Methods and get Methods (Cont.) set and get methods A class’s private fields can be manipulated only by the class’s methods. A client of an object calls the class’s public methods to manipulate the private fields of an object of the class. Classes often provide public methods to allow clients to set (i.e., assign values to) or get (i.e., obtain the values of) private instance variables. The names of these methods need not begin with set or get, but this naming convention is recommended. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Primitive Types vs. Reference Types Types are divided into primitive types and reference types. The primitive types are boolean, byte, char, short, int, long, float and double. All nonprimitive types are reference types, such as strings and classes. A primitive-type variable can store exactly one value of its declared type at a time. Primitive-type instance variables are initialized by default—variables of types byte, char, short, int, long, float and double are initialized to 0, and variables of type boolean are initialized to false. You can specify your own initial value for a primitive-type variable by assigning the variable a value in its declaration. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Primitive Types vs. Reference Types Programs use variables of reference types (normally called references) to store the locations of objects in the computer’s memory. Such a variable is said to refer to an object in the program. Reference-type instance variables are initialized by default to the value null A reserved word that represents a “reference to nothing.” When using an object of another class, a reference to the object is required to invoke (i.e., call) its methods. Also known as sending messages to an object. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Initializing Objects with Constructors When an object of a class is created, its instance variables are initialized by default. Each class can provide a constructor that initializes an object of a class when the object is created. Java requires a constructor call for every object that is created. Keyword new requests memory from the system to store an object, then calls the corresponding class’s constructor to initialize the object. A constructor must have the same name as the class. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Initializing Objects with Constructors (Cont.) By default, the compiler provides a default constructor with no parameters in any class that does not explicitly include a constructor. Instance variables are initialized to their default values. Can provide your own constructor to specify custom initialization for objects of your class. A constructor’s parameter list specifies the data it requires to perform its task. Constructors cannot return values, so they cannot specify a return type. Normally, constructors are declared public. If you declare any constructors for a class, the Java compiler will not create a default constructor for that class. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Thank You ! Reading Paul Deitel, “Java How to Program, 9/E”, Publisher: Prentice Hall, 2012, ISBN-10: 0132575663 ISBN-13: 9780132575669 3.1 – 3.6 © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.