1 / 120

Objects and Classes --

Objects and Classes --. Now that some low-level programming concepts have been established, we can examine objects in more detail Chapter 4 focuses on: the concept of objects the use of classes to create objects using predefined classes defining methods and passing parameters

montana
Télécharger la présentation

Objects and Classes --

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. Objects and Classes -- • Now that some low-level programming concepts have been established, we can examine objects in more detail • Chapter 4 focuses on: • the concept of objects • the use of classes to create objects • using predefined classes • defining methods and passing parameters • defining classes • visibility modifiers • static variables and methods • method overloading

  2. Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields

  3. Writing Classes • The programs we’ve written in previous examples have used classes defined in the Java standard class library • Now we will begin to design programs that rely on classes that we write ourselves • The class that contains the main method is just the starting point of a program • True object-oriented programming is based on defining classes that represent objects with well-defined characteristics and functionality

  4. Objects • An object has: • behaviors - what it can do (or be done to it) • state - characteristics that describe its being For example, a particular bank account • has an account number • has a current balance • can be deposited into • can be withdrawn from • Or, a circle could be stored as an object with variables describing its’ size, and a method that draws it on the screen or calculates its’ area.

  5. Objects • An object has: • state - descriptive characteristics • behaviors - what it can do (or be done to it) • For example, consider a coin that can be flipped so that it's face shows either "heads" or "tails” • The state of the coin is its current face (heads or tails) • The behavior of the coin is that it can be flipped • Note that the behavior of the coin might change its state

  6. Objects • Objects often (but not always) model real world objects and contain variable and methods to describe it. • An Object must have a unique identity to distinguish it from all other objects. • Even if two objects have the same state and variables, they would have to have different names in the program. • An object’s behavior often modifies its state. When a ball rolls, it changes location.

  7. Objects • Two objects can have the same state. Two BMW’s could have the same motors, leather, color etc., but they would be completely different entities defined by their name. E.g. My BMW, Jessie’s BMW, or Kyles’s BMW and John’s BMW2. • Objects do not have to be tangible objects. They can be integers or error messages or exceptions. • The methods that an object contains define its operations - what it can do and what can be done to it. • Everything an object can do, everything that describes it is defined by its class.

  8. Classes • A class is a blueprint of an object • It is the model or pattern from which objects are created • For example, the String class is used to define String objects • Each String object contains specific characters (its state) • Each String object can perform services (behaviors) such as .toUpperCase

  9. Classes • The String class was provided for us by the Java standard class library. • But we can also write our own classes that define specific objects that we need. • For example, suppose we wanted to write a program that simulates the flipping of a coin. • We could write a Student class to represent a students in program that keeps track of student data.

  10. int x, y; char ch; Classes • A class contains data declarations and method declarations Data declarations- define its state Method declarations - Define its behavior

  11. Classes • A class defines the methods and types of data associated with an object. • Creating an object from a class is called instantiation; an object is an instance of a particular class. • Once you have defined a class, you can define many different instances with different features

  12. Instances of objects • An instance of an object is another word for an actual object, it is a concrete representation. • A class is a generic representation of an object. • The Customer class could describe many bank accounts, but toms_savings is a particular bank account with a particular balance

  13. Objects • An instance and an object are the same thing, both are concrete representations of their class. • The newoperator creates an object from a class: Customer toms_savings = new Customer(); • This declaration asserts that toms_savings is a variable that refers to an object created from the Customerclass

  14. Creating Objects - Instantiation • The new operator creates an instance of a class and reserves memory for it. • The newly created object is set up by a call to a constructor of the Customer class. • Whenever you use the new operator, a special method defined in the given class ( a constructor) is called.

  15. Object References • The declaration of the objectreference variable and the creation of the object can be separate activities: Customertoms_savings;// declares the variable // now has memory allocated for its data toms_savings = newCustomer (125.89);

  16. Instantiation and References int num = 115; • num is variable of type int that is initialized to 115. When used in the program, it is evaluated to the value 115. Chess_Piece pawn = new Chess_Piece(); • pawn, on the other hand, is a variable that refers to an object of the class Chess_Piece. The new operator calls the constructor of the Chess_Piece class. • Until the constructor is called with the new operator, no memory is set aside for the pawn object. Each object has its own memory space

  17. Constructors If we declare: Boat carnival; carnival = new Boat(); • In the first line, carnival is a reference to an object of the class Boat. • No memory is yet allotted to it. It is not yet instantiated. • References hold the address of the memory location where the object is stored. • Until the new operator is called and carnival is initialized, carnival does not refer to any data in memory.

  18. Constructors • A constructor is a special method used to initialize or create an object. • It initializes the new object and its variables, i.e., allocates memory for it. • It must have the same name as the class. • It can have parameters, which are often used to initialize some variables in the object.

  19. Constructors • For example, theconstructor for the Customer class could take a parameter specifying its initial balance: Customer toms_savings = new Customer (“Tom, 125.89); • The 125.89 is a value used to initialize a variable called balance defined in the Customer class. “Tom” will stored as the customer’s name. • In the Customer class, the Constructor method receives the 125.89 and Tom values sent to it from the statement in main:

  20. class Customer: { private String name; private int balance;// data that describes a customer public Customer( String name1, double NewBalance) { name1 = name; // constructor balance = NewBalance; } Customer toms_savings = new Customer (“Tom, 125.89); • We call the constructor with the above code and it creates a new customer account with an initial balance of 125.89 and the name of “Tom”

  21. class Customer { private double Balance; // instance variables private name; public Customer(String Name1,double NewBalance) { Balance = NewBalance; // constructor name = name1; } …. …….. public double returnBalance () // method to return balance { return Balance; } } // close class

  22. Constructors • A constructor: • Is a special method that is used to set up a newly created object. • Often sets the initial values of variables. • Always has the same name as the class. • Does not return a value. • Has no return type, not evenvoid. • The programmer does not have to define a constructor for a class. Java will define a generic constructor.

  23. Creating Classes • The syntax for defining a class is: class class-name { //class declaration declarations of variables constructors // class body methods } • The class declaration declares the name of the class along with other attributes. • The variables, constructors, and methods of a class are generically called members of the class.

  24. Classes • The values given to data in a class define the state of an object created from the class • Methods define the behaviors of the object • For our Die class, we might declare an integer that represents the current value showing on the face • One of the methods would “roll” the die by setting that value to a random number between one and six

  25. Classes • We’ll want to design the Die class with other data and methods to make it a versatile and reusable resource • Any given program will not necessarily use all aspects of a given class • See RollingDice.java (page 157) • See Die.java (page 158)

  26. The Die Class • The Dieclass contains two data values • a constant MAX that represents the maximum face value • an integer faceValuethat represents the current face value • The rollmethod uses the random method of the Math class to determine a new face value • There are also methods to explicitly set and retrieve the current face value at any time

  27. The toString Method • All classes that represent objects should define a toString method • The toString method returns a character string that represents the object in some way • It is called automatically when an object is concatenated to a string or when it is passed to theprintlnmethod

  28. Instance Data • The faceValue variable in the Die class is called instance databecause each instance (object) that is created has its own version of it • A class declares the type of the data, but it does not reserve any memory space for it • Every time a Die object is created, a new faceValue variable is created as well • The objects of a class share the method definitions, but each object has its own data space • That's the only way two objects can have different states

  29. die1 faceValue 5 die2 faceValue 2 Instance Data • We can depict the two Die objects from the RollingDice program as follows: Each object maintains its own faceValue variable, and thus its own state

  30. class Rectangle class Rectangle { int length, width; // instance data public Rectangle( ) { // constructor length = 10; width = 12; } • Java supports name overloading for constructors so that a class can have any number of constructors, all of which have the same name.

  31. Overloaded Constructors • Another constructor that could be defined by Rectangle: public Rectangle(int Newlength, int Newwidth) { length = Newlength; width = Newwidth } • Both constructors share the same name, Rectangle, but they have different parameter lists. • The compiler determines which constructors to use based on the number and types of the parameters/

  32. Overloading Constructors • An overloaded constructor provides multiple ways to set up a new object • See SnakeEyes.java (page 203) • See Die.java (page 204)

  33. Constructor • When creating an object, choose the constructor whose arguments best reflect how you want to set up the new object. • The compiler can determine which constructor to use. based on the number and type of the arguments that you pass into the constructor. • The instance variables in your class need to have data assigned to them. You should use the constructor to give them these values.

  34. Outline Anatomy of a Class Anatomy of a Method Encapsulation Graphical Objects Graphical User Interfaces Buttons and Text Fields

  35. Objects • Once an object exists, its methods can be invoked using the dot operator: Customer toms_savings = new Customer (125.89); toms_savings.deposit (35.00); • This invokes the deposit method in the toms_savings object. Place the dot right after the object reference name toms_savings. • Variables could be accessed also using the dot operator.

  36. Classes and Objects • A class defines the data types for an object, but a class does not store data values. • Each object has its own unique data space. • The variables defined in a class are called instance variables because each instance of the class has its own variables. • All methods in a class have access to all instance variables of the class. • Methods are shared among all objects of a class.

  37. References • An object reference holds the memory address of an object Chess_Piece bishop1 = new Chess_Piece(); • All interaction with an object occurs through a reference variable. • A reference variable holds the address in memory where its instance variables and methods are stored. bishop1

  38. Before After bishop1 bishop2 bishop1 bishop2 Reference Assignment • For object references, the value of the memory location is copied so that bishop1 points to same location bishop1 does: bishop2 = bishop1; Lost!

  39. Object Variables • When you create an object with : Chesspiece bishop = new Chesspiece(); • You are creating a “handle” which you can use to obtain, or change the value of the object variable - bishop. You can make bishop point to another location in memory.

  40. Objects • Primitive variables likenumdon’t act this way. Two primitive variables can hold the same number but they refer to different locations in memory. • You can’t change a and b’s location in memory. • int a = 32; a b int b = 32; • You can also have two or more handles to the object bishop by creating aliases for it. 32 32

  41. Before After num1 num2 num1 num2 5 12 5 5 Assignment • The act of assignment takes a copy of a value and stores it in a variable • For primitive types: num2 = num1;

  42. Aliases • Two or more references that refer to the same object are called aliases of each other. There is only one copy of the object (and its’ data), but with multiple ways to access it. • Each alias object contains the same memory address. • Aliases can be useful, but should be managed carefully • If you change the state of one object, you also the change the state of all its aliases, because they refer to the same object.

  43. Garbage Collection • When an object is lost as in the previous example - it no longer has a object referring to it, it is cleaned up automatically by Java with garbage collection, • Therefore, when an object no longer has any valid references to it, it can no longer be accessed by the program. • It is useless, and therefore called garbage • Java performs automatic garbage collection periodically, returning an object's memory to the system for future use.

  44. Visibility Modifiers • In Java, we accomplish encapsulation through the appropriate use of visibility modifiers • A modifier is a Java reserved word that specifies particular characteristics of a method or data value • We've used the modifier final to define a constant • Java has three visibility modifiers: public, private, and protected • We will discuss the protected modifier more completely when we get to inheritance.

  45. Visibility Modifiers • Members of a class that are declared with public visibility can be accessed from anywhere • Members of a class that are declared with private visibility can only be accessed from inside the class • Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package • Java modifiers are discussed in detail in Appendix F

  46. Visibility Modifiers • As a general rule, no object's data should be declared with public visibility • Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients. • Public methods are also called service methods • A method created simply to assist a service method is called a support method. • Since a support method is not intended to be called by a client, it should not be declared with public visibility.

  47. public private Variables Methods Visibility Modifiers Violate encapsulation Enforce encapsulation Support other methods in the class Provide services to clients

  48. Protected • The next access level specifier is protected, which allows the class itself, subclasses and all classes in the same package to access the members. • Use the protected access level when it's appropriate for a class's subclasses to have access to the member classes. • This modifier is more important we study Inheritance. • The protected specifier affects access for classes in the same package?

  49. Writing Methods • A method declaration specifies the code that will be executed when the method is invoked (or called) • When a method is invoked, the flow of control jumps to the method and executes its code • When complete, the flow returns to the place where the method was called and continues • The invocation may or may not return a value, depending on how the method was defined

  50. compute myMethod myMethod(); Method Control Flow • The called method could be within the same class, in which case only the method name is needed

More Related