Download presentation
Presentation is loading. Please wait.
Published byWarren Raymond Carter Modified over 9 years ago
1
CISC6795 Spring 11 Fordham Univ. Introduction to Classes and Objects 1
2
Outline Why object-orientation? History of object-orientation Example Key concepts: class, object: state and behavior => instance variablale and method Nuts and bolts of object-oriented programming Reference variable and primitive variable Pass-by-value Constructor Case studies 2
3
What is OOP ? Object-oriented programming (OOP) is a programming paradigm using objects – data structures consisting of data fields and methods, – together with their interactions to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, messaging, modularity, polymorphism, and inheritance. Based on article on Wikipedia 3
4
Different programming languages Machine language Each instruction is a string of 0 and 1 bits. Each instruction is executed using a small # of electronic circuits. Assembly Language A symbolic representation of machine language Compiler Language Interpreter Language Perl, Python, BASH, … All programming languages provide abstractions. 4
5
Assembly language Assembly languages first developed in 1950s Free programmers from tedium such as remembering numeric codes and calculating addresses. Typically provides following mechanisms Opcode mnemonic: a symbolic name for machine language instruction e.g., MOV EAX, [EBX] Data Sections: define data elements for hold data & variables Assembly directive: handled by assembler, e.g., to reserve storage areas Macros: extended by assembler Like C macros, e.g. #define min(X, Y) ((X) < (Y) ? (X) : (Y)) 5
6
Assembly language (cont’d) By 1980s (1990s on microcomputers), their use had largely been supplanted by high-level languages for improved programming productivity. Assembly language still used in device drivers, low-level embedded systems, and real-time systems direct hardware manipulation access to specialized processor instructions address critical performance issues 6
7
High level language High level languages such as FORTRAN, BASIC, and C are abstractions of assembly language Programmer still thinks in terms of computer structure rather than problem structure Programmer must establish association between: machine model (in “solution space,”), which is the place where you’re implementing that solution, such as a computer the model of the problem that is actually being solved (in the “problem space,” which is the place where the problem exists, such as a business). 7
8
Object-Oriented Language Provide tools for programmer to represent elements in problem space We refer to the elements in problem space and their presentations in solution space as “objects.” This representation is general enough that programmer is not constrained to any particular type of problem. Program is allowed to adapt itself to problem domain by adding new types of objects, so when you read the code describing the solution, you’re reading words that also express the problem. 8
9
Object-Oriented language OOP: a more flexible and powerful language abstraction programmer describes problem in terms of the problem, rather than in terms of computer There’s still a connection back to the computer Each object looks quite a bit like a little computer—it has a state, and it has operations that you can ask it to perform. 9
10
Class vs object Object-oriented programming language is extensible Programmer defines a new type of (similar) objects as a class 10
11
Object has data fields and methods 11 Classes contain attributes, i.e., instance variables, fields Carried with the object as it is used Class provides methods Describes the mechanisms that actually perform its tasks Hides from its user the implementation details
12
Example: Cashier Register class Things that a Cashier Register knows Things that a Cashier Register does 12
13
Outline Why object-orientation? History of object-orientation Key concepts: class, object: state and behavior => instance variable and method Nuts and bolts of object-oriented programming Through the example of GradeBook class Reference variable and primitive variable Pass-by-value Constructor Case studies 13
14
GradeBook Class A class that represents a grade book kept by professor to store and analyze a set of student grades Instance variables (characteristics) courseName (a string type) grades (array of integers) Methods (behavior) setCourseName, getCourseName, outputGrades, getAverage, outputBarChart, … 14
15
Instance variable courseName 15 Class Declaration for GradeBook
16
Class Declaration public class GradeBook { … } Class declarations: access modifier, keyword class, class name, pair of left and right braces keyword public is an access modifier Each class declaration that begins with keyword public must be stored in a file that has same name as the class and ends with.java file-name extension. JVM locates the class by the file name of the.class name. A.java file can contain more than one class But only one class in each.java file can be public Declaring more than one public class in same file is a compilation error. 16 Body of class declaration head of class declaration
17
Class Declaration: body Enclosed by { and }. Instance variable declarations private string courseName; Method declarations: head and body of all class methods Good coding conventions: Always list instance variables first See the names and types of the variables before you see them used in the methods of the class. Place a blank line between method declarations to separate the methods and enhance program readability. 17
18
Access Modifiers public and private Precede each instance variable and method declaration with an access modifier Default modifier if none is specified ? private variables and methods are accessible only to methods of the class in which they are declared Data hiding: declaring instance variables private Private variables and methods are accessible to all, i.e., any classes Instance variables should be declared private and methods should be declared public. Sometimes we declare certain methods private, then they can be accessed only by other methods of the class.) 18
19
Instance Variables private string courseName; Instance variables: variables declared in a class declaration Also called fields or data members Representing attributes of the class object Each object of the class has a separate instance of the variable Student class has name, birthday, year, … attributes Scope: the whole class, i.e., all member functions can access instance variables Recall: local variables are variables declared in the body of method Scope: within that method Shadowing: local variables or parameter variables shadow instance variable with same name 19
20
Class method declaration 20 Method declaration: Head: access modifier, return type, name of method Body: statements enclosed by paranthesis Note that there is no static keyword in header for these methods They are not static method (or class method) Cannot be invoke on the class: GradeBook.setCourseName (“CISC6795”) Need to invoke on an object of this class
21
2005 Pearson Education, Inc. All rights reserved. set and get methods private instance variables cannot be accessed directly by clients of the class Use set methods to alter the value of private instance variables public void setCourseName ( String name) advantages: perform data checking to ensure data consistency Use get methods to retrieve the value of private instance variables public String getCourseName () 21
22
GradeBookTest: a client of GradeBook class 22 Call get method for courseName Class Declaration for GradeBookTest
23
23 Call set method for courseName Call displayMessage Default initial value provided for all fields not initialized Equal to null for String s
24
Application with Multiple Classes Compiling commands java GradeBook.java GradeBookTest.java List each.java file separately separated with spaces java *.java Compile with *.java to compile all.java files in that directory Executing the application: java GradeBookTest ## the name of the class that defines a ##main() which you want to executes 24
25
Notes on Import Declarations We learn that we need to import classes that are used in current class Otherwise, use fully qualified name: java.util.Scanner input = new java.util.Scanner (System.in); Java imports following packages by default: java.lang Classes compiled in the same directory are implicitly imported into source code of other files in directory 25
26
Outline Why object-orientation? History of object-orientation Example Key concepts: class, object: state and behavior => instance variablale and method Nuts and bolts of object-oriented programming Reference variable and primitive variable Pass-by-value Constructor Case studies 26
27
Primitive types: boolean, byte, char, short, int, long, float, double A primitive variable => a cup with name, size (type), and content Name: name of variable Size is measured in bits Content is the value of the variable stored as bits Reference type (or, nonprimitive types) Size: all reference variable have same size Content: bits representing a way to get to (access) a specific object Default value of null How JVM does it ? Pointers … Primitive Types vs. Reference Types 27
28
Primitive Types vs. Reference Types 28
29
29 Call methods on the Dog object through remote control (i.e., reference variable): myDog.bark()
30
Primitive Types vs. Reference Types A variable’s declared type indicates whether the variable is of a primitive or a reference type If a variable’s type is not one of the eight primitive types, then it is a reference type. For example, Account account1 indicates that account1 is a reference to an Account object E.g., array date type is a reference type int [] array = new int[20]; 30 Java variables are either primitive type or reference type. All parameters in method calls are pass-by-value.
31
Outline Why object-orientation? History of object-orientation Example Key concepts: class, object: state and behavior => instance variablale and method Nuts and bolts of object-oriented programming Reference variable and primitive variable Constructors Case studies 31
32
Constructors Constructors: special method to initialize an object of a class Called when an object is the class is created new Dog ( ); new Scanner (System.in); Java requires a constructor for every class Java will provide a default no-argument constructor if none is provided Instance variables are initialized with default value Default values are zero for primitive numeric types, false for boolean values and null for references Unless default value for instance variables is acceptable, provide a constructor 32
33
double variable balance
34
Format specifier %f : to output floating-point numbers Place a decimal and a number between the percent sign and the f to mandate a precision
35
Input a double value
36
Output a double value
37
Overloaded Constructors Overloaded constructors Provide multiple constructor definitions with different signatures No-argument constructor: the constructor invoked without arguments this reference can be used to invoke another constructor Allowed only as the first statement in a constructor’s body A constructor can call methods of the class. However: instance variables might not yet be in a consistent state, because constructor is in process of initializing object. Using instance variables before they have been initialized properly is a logic error. 37
38
Outline Time2.java (1 of 4) 38 No-argument constructor Invoke three-argument constructor
39
Outline Time2.java (2 of 4) 39 Call setTime method Constructor takes a reference to another Time2 object as a parameter Could have directly accessed instance variables of object time here When implementing a method of a class, use set and get methods to access the class’s private data. This simplifies code maintenance and reduces likelihood of errors.
41
41
42
Outline Time2Test.java (1 of 3) 42 Call overloaded constructors
43
Outline Time2Test.java (2 of 3) 43
44
Outline Time2Test.java (3 of 3) 44
45
Common Programming Error 5 If a class has constructors, but none of the public constructors are no-argument constructors, and a program attempts to call a no-argument constructor to initialize an object of the class, a compilation error occurs. A constructor can be called with no arguments only if the class does not have any constructors (in which case the default constructor is called) or if the class has a public no-argument constructor. 45
46
Software Engineering Observation 6 Java allows other methods of the class besides its constructors to have the same name as the class and to specify return types. Such methods are not constructors and will not be called when an object of the class is instantiated. Java determines which methods are constructors by locating the methods that have the same name as the class and do not specify a return type. 46
47
Outline private instance variables Declare public method setTime Validate parameter values before setting instance variables 47
48
Outline 48 format strings String method format is similar to System.out.printf except it returns a formatted string instead of displaying it in a command window
49
2005 Pearson Education, Inc. All rights reserved. Outline Why object-orientation? History of object-orientation Example Key concepts: class, object: state and behavior => instance variabale and method Nuts and bolts of object-oriented programming Reference variable and primitive variable Constructors Case studies: Time class 49
50
Outline private instance variables Declare public method setTime Validate parameter values before setting instance variables 50
51
Outline 51 format strings String method format is Similar to System.out. printf except it returns a formatted string instead of displaying it in a command window
52
Time Class Case Study public services (or public interface) public methods available for a client to use Instance variables Can be initialized when they are declared or in a constructor Should maintain consistent (valid) values Methods that modify instance variables should verify that the intended new values are proper. If they are not, the set methods should place the private variables into an appropriate consistent state. 52
53
Software engineering observations A class’s public interface public methods: a view of the services the class provides to the class’s clients A class’s implementation details private variables and private methods are not accessible to the class’s clients An attempt by a method that is not a member of a class to access a private member of that class is a compilation error. 53
54
Software Engineering Observation Classes simplify programming, because the client can use only the public methods exposed by the class. Such methods are usually client oriented rather than implementation oriented. Clients are neither aware of, nor involved in, a class’s implementation. Clients generally care about what the class does but not how the class does it. Interfaces change less frequently than implementations. When an implementation changes, implementation-dependent code must change accordingly. Hiding the implementation reduces the possibility that other program parts will become dependent on class-implementation details. 54
55
Call toUniversalString method Call toString method new implicitly invokes Time1 ’s default constructor
56
Call setTime method Call setTime method with invalid values
57
Outline MemberAccessTest.java 57 Attempting to access private instance variables
58
non-static method & this Reference Any non-static method must be called upon with an object Time1.toString(); ## leads to compilation error ! Time1 t = new Time1; ## create Time1 object and use t to reference it t.toString(); ## call toString() method upon a Time1 object referenced by t Non-static method can access this reference, a reference to the object on which it is called upon implicitly use this when referring to the object’s instance variables and other methods can be explicitly used to access instance variables when they are shadowed by local variables or method parameters 58
59
2005 Pearson Education, Inc. All rights reserved. Performance Tip Java maintains: only one copy of each method per class—this method is invoked by every object of the class. One copy of non-static instance variables per object Each method of the class implicitly uses this to determine the specific object of the class to manipulate. 59
60
Declare instance variables Method parameters shadow instance variables Using this to access the object’s instance variables
61
Using this explicitly and implicitly to call toUniversalString Use of this not necessary here
62
Common Programming Error It is often a logic error when a method contains a parameter or local variable that has the same name as a field of the class. Use reference this if you wish to access the field of the class—otherwise, the method parameter or local variable will be referenced. Avoid method parameter names or local variable names that conflict with field names. This helps prevent subtle, hard-to- locate bugs. 62
63
Composition Composition: a class can have references to objects of other classes as members Sometimes referred to as a has-a relationship One form of software reuse is composition Example: each employee has the following attributes: Name Gender Birthdate Hire date … Some of the attributes are objects themselves More accurately: an object reference 63
65
Validates month value Validates day value
66
Check if the day is February 29 on a leap year
67
Employee contains references to two Date objects Implicit calls to hireDate and birthDate ’s toString methods If a constructor is not provided, what will be the default values for each field ?
68
Create an Employee object Display the Employee object
69
Summary Why object-orientation? History of object-orientation Example Key concepts: class, object: state and behavior => instance variablale and method Nuts and bolts of object-oriented programming Reference variable and primitive variable Pass-by-value Constructors Case studies: Time class 69
70
Disclaimer This presentation uses materials from Head First Java Java How to Program, slides set 70
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.