1 / 70

Introduction to Classes and Objects

This introduction provides an overview of object-oriented programming, its key concepts, and the history behind it. It also explores different programming languages and their abstractions, including assembly language and high-level languages. The benefits of using object-oriented languages are explained, along with a brief example of a Cashier Register class. The GradeBook class is used as a case study to further illustrate the concepts of instance variables, methods, and class declarations.

taborp
Download Presentation

Introduction to Classes and Objects

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Classes and Objects CISC6795 Spring 11 Fordham Univ.

  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

  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

  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.

  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))

  6. Assembly language (cont’d) • By 1980s (1990s on microcomputers), their use had largely been supplanted by high-level languagesfor 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

  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).

  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.

  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.

  10. Class vs object • Object-oriented programming language is extensible • Programmer defines a new type of (similar) objects as a class

  11. Object has data fields and methods • 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

  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

  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, …

  15. Instance variable courseName 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. head of class declaration Body 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.

  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.)

  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

  20. Class method declaration • 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. 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 ()

  22. Call get method for courseName GradeBookTest: a client of GradeBook class Class Declaration for GradeBookTest

  23. Call set method for courseName Call displayMessage • Default initial value provided for all fields not initialized • Equal to null for Strings

  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

  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

  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

  27. Primitive Types vs. Reference Types • 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 • Contentis 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 …

  28. Primitive Types vs. Reference Types

  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]; 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

  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

  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.

  38. Outline • Time2.java • (1 of 4) No-argument constructor Invoke three-argument constructor

  39. Outline Call setTime method • Time2.java • (2 of 4) 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.

  40. Outline Call overloaded constructors • Time2Test.java • (1 of 3)

  41. Outline • Time2Test.java • (2 of 3)

  42. Outline • Time2Test.java • (3 of 3)

  43. Common Programming Error • 5If a class has constructors, but none of the publicconstructors 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.

  44. Software Engineering Observation • 6Java 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.

  45. Outline private instance variables Declare public method setTime Validate parameter values before setting instance variables

  46. Outline 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

  47. 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

  48. Outline private instance variables Declare public method setTime Validate parameter values before setting instance variables

More Related