1 / 80

Lecture 7 Defining Classes

Lecture 7 Defining Classes. Richard Gesick. Topics. Defining a Class Defining Instance Variables Writing Methods The Object Reference this The toString and equals Methods static Members of a Class enum Types. Why User-Defined Classes?.

simone
Download Presentation

Lecture 7 Defining 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. Lecture 7Defining Classes Richard Gesick

  2. Topics • Defining a Class • Defining Instance Variables • Writing Methods • The Object Reference this • ThetoString and equals Methods • static Members of a Class • enum Types

  3. Why User-Defined Classes? Primitive data types (int, double, char, .. ) are great … … but in the real world, we deal with more complex objects: products, websites, flight records, employees, students, .. Object-oriented programming enables us to manipulate real-world objects.

  4. Why User-Defined Classes? • An object is a run-time entity that contains data and responds to messages. • A class is a software package or template that describes the characteristics of similar objects. • These characteristics are of two sorts: • Variable declarations that define an object’s data requirements (instance variables). • Methods that define its behavior in response to messages.

  5. User-Defined Classes • Combine data and the methods that operate on the data • Advantages: • The class methods are responsible for the validity of the data. • Implementation details can be hidden. • A class can be reused.

  6. User-Defined Classes The combining of data and behavior into a single software package is called encapsulation. An object is an instance of its class, and the process of creating a new object is called instantiation Clientof a class: A program that instantiates objects and calls the methods of the class

  7. Classes, Objects, and Computer Memory • When a Java program is executing, the computers memory must hold: • All class templates in their compiled form • Variables that refer to objects • Objects as needed • Each method’s compiled byte code is stored in memory as part of its class’s template.

  8. Classes, Objects, and Computer Memory • Memory for data is allocated within objects. • All class templates are in memory at all times, individual objects come and go. • An object first appears and occupies memory when it is instantiated, and it disappears automatically when no longer needed.

  9. The Internal Structure of Classes and Objects • The JVM knows if an object is in use by keeping track of whether or not there are any variables referencing it. • Because unreferenced objects cannot be used, Java assumes that it is okay to delete them from memory via garbage collection.

  10. Three Characteristics of an Object • An object has behavior as defined by the methods of its class • An object has state, which is another way of saying that at any particular moment its instance variables have particular values. • Typically, the state changes over time in response to messages sent to the object.

  11. Objects • An object has its own unique identity, which distinguishes it from all other objects in the computers memory. • An objects identity is handled behind the scenes by the JVM and should not be confused with the variables that might refer to the object. • When there are no variables the garbage collector purges the object from memory.

  12. Clients, Servers, and Interfaces • When messages are sent, two objects are involved: • The sender (the client) • The receiver (the server) • Client: • A clients interactions with a server are limited to sending it messages. • A client needs to know only a servers interface, that is, the list of methods supported by the server.

  13. Server • The server’s data requirements and the implementation of its methods are hidden from the client (information hiding). • Only the person who writes a class needs to understand its internal workings • A class’s implementation details can be changed radically without affecting any of its clients provided its interface remains the same.

  14. Syntax for Defining a Class accessModifier class ClassName { // class definition goes here } ***Note that the curly braces are required.

  15. SOFTWARE ENGINEERING TIP Use a noun for the class name. Begin the class name with a capital letter.

  16. Important Terminology • Fields • instance variables: the data for each object • class data: static data that all objects share • Members • fields and methods • Access Modifier • determines access rights for the class and its members • defines where the class and its members can be used

  17. Access Modifiers

  18. public vs. private • Classes are usually declared to be public. • Instance variables are usually declared to be private. • Methods that will be called by the client of the class are usually declared to be public. • Methods that will be called only by other methods of the class are usually declared to be private. APIs of methods are published (made known) so that clients will know how to instantiate objects and call the methods of the class.

  19. Defining Instance Variables Syntax: accessModifierdataTypeidentifierList; dataType can be primitive data type or a class type identifierList can contain: • one or more variable names of the same data type • multiple variable names separated by commas • initial values • Optionally, instance variables can be declared as final.

  20. Examples of Instance Variable Definitions private String name = ""; private final int PERFECT_SCORE = 100, PASSING_SCORE = 60; private intstartX, startY, width, height;

  21. SOFTWARE ENGINEERING TIP Define instance variables for the data that all objects will have in common. Define instance variables as private so that only the methods of the class will be able to set or change their values. Begin the instance variable identifier with a lowercase letter and capitalize internal words.

  22. The Auto Class public class Auto { private String model; private int milesDriven; private double gallonsOfGas; } The Auto class has three instance variables: model, milesDriven, and gallonsOfGas.

  23. Writing Methods Syntax: accessModifierreturnTypemethodName( parameter list ) // method header { // method body } parameter list is a comma-separated list of data types and variable names. • to the client, these are arguments • to the method, these are parameters The parentheses are required even if the method takes no parameters. **Note that the method header is the method’s API.

  24. SOFTWARE ENGINEERING TIP Use verbs for method names. Begin the method name with a lowercase letter and capitalize internal words.

  25. Method Return Types • The return type of a method is the data type of the value that the method returns to the caller. The return type can be any of Java's primitive data types, any class type, or void. • Methods with a return type of void do not return a value to the caller.

  26. Method Body • The code that performs the method's function is written between the beginning and ending curly braces. • Unlike if statements and loops, these curly braces are required, regardless of the number of statements in the method body. • In the method body, a method can declare variables, call other methods, and use any of the program structures we've discussed, such as if/else statements, while loops, for loops, switch statements, and do/while loops.

  27. main is a Method public static void main( String [] args ) { // application code } Let's look at main'sAPI in detail: publicmain can be called from outside the class. (The JVM calls main.) staticmain can be called by the JVM without instantiating an object. void main does not return a value String [] argsmain's parameter is a String array

  28. Value-Returning Methods • Use a return statement to return a value • Syntax: return expression; Note: All possible execution paths in the method must return a value. Thus, a method can have multiple return statements.

  29. Return Statements If a method has a return type, its implementing code must have at least one return statement that returns a value of that type. There can be more than one return statement in a method; however, the first one executed ends the method. A return statement in a void method quits the method and returns nothing.

  30. Return Statements • The following is an example of a method that has two return statements but executes just one of them: boolean odd(int i) { if (i % 2 == 0) return false; else return true; }

  31. Return Statements • The following is an example of a method that a return statement but no return type public static void A(int n) { if (n <= 0) return; n--; B(n); }

  32. Constructors • Special methods that are called automatically when an object is instantiated using the new keyword. • A class can have several constructors. • The job of the class constructors is to initialize the instance variables of the new object.

  33. Defining a Constructor Syntax: public ClassName( parameter list ) { // constructor body } Note: constructors have no return value, not even void! • Each constructor must have a different number of parameters or parameters of different types. Default constructor: a constructor that takes no arguments.

  34. Default Initial Values If the constructor does not assign values to the instance variables, they receive default values depending on the instance variable’s data type.

  35. Common Error Trap Do not specify a return value for a constructor (not even void). Doing so will cause a compiler error in the client program when the client attempts to instantiate an object of the class.

  36. A Class to describe a Ball • A class consists of methods that describe features of an object. • Constructors instantiate (make) the object. A class will normally have at least 2 constructors, a default constructor and at least one that receives additional parameters. • Constructors are activated when the keyword new is used and at no other time. • A constructor is never used to reset instance variables of an existing object.

  37. a Ball Class • If a class contains no constructors the JVM provides a primitive default constructor. • This constructor initializes numeric variables to zero and object variables to null, thus indicating that the object variables currently reference no objects. • Accessors are methods that return one of the object's values to the driver program. • Mutatorsare methods that change one of the objects values.

  38. General methods • A method has this general format. • visibility type return type method name parameters • an accessor (returns a particular value from the class • public double getRadius( ) • { //code to be executed such as return radius • } • a mutator ( modifies value(s) of the class) • public void setColor( Color c) • { // code to be executed such as color = c; • }

  39. Accessor Methods Clients cannot directly access private instance variables, so classes provide publicaccessor methods with this standard form: public returnTypegetInstanceVariable( ) { return instanceVariable; } (returnTypeis the same data type as the instance variable)

  40. Accessor Methods Example: the accessor method for radius public double getRadius( ) { return radius; }

  41. Mutator Methods Mutator methods allow the client to change the values of instance variables. They have this general form: public void setInstanceVariable(dataType value ) { // if value is valid, // assign value to the instance variable }

  42. Mutator Methods Example: the mutator method for radius public void setRadius( int newRadius) { if ( newRadius>= 0 ) radius = newRadius; else { System.err.println(“radius cannot be negative."); System.err.println( "Value not changed." ); } }

  43. SOFTWARE ENGINEERING TIP Write the validation code for the instance variable in the mutator method and have the constructor call the mutator method to validate and set initial values. This eliminates duplicate code and makes the program easier to maintain.

  44. Common Error Trap Do not declare method parameters. Parameters are already defined and are assigned the values sent by the client to the method. Do not give the parameter the same name as an instance variable. The parameter has name precedence so it "hides" the instance variable. Do not declare a local variable with the same name as an instance variable. Local variables have name precedence and hide the instance variable.

  45. Data Manipulation Methods Perform the "business" of the class. Example: a method to calculate volume of a ball: public double calculateVolume( ) { double v= 4.0/3*Math.PI*radius*radius*radius; return v; }

  46. A Ball Class • Before writing any code, brainstorm a bit. What features to you want your class to have? For a actual physical object it is easier than with something that is more abstract. • What are the features of a ball? • My features of a ball: • color, name, radius, diameter, circumference,volume, surface area

  47. writing the class • Writing the class becomes easier with practice. The best way to do this is to have 2 panels up on your screen, one for the driver program ( it has main) and one for the class. That way as you get each method of the class written, you can debug it and ensure that it works properly before going to far. • You will also have to start determining which variables we will use in the class that need to be available to all methods in the class. These are normally identified as private and declared outside of any methods.

  48. Writing the class

  49. Class Scope • Instance variables have class scope, meaning that: • A constructor or method of a class can directly refer to instance variables. • Methods also have class scope, meaning that: • A constructor or method of a class can call other methods of a class (without using an object reference).

  50. Local Scope • A method's parameters have local scope,meaning that: • a method can directly access its parameters. • a method's parameters cannot be accessed by other methods. • A method can define variables which also have local scope, meaning that: • a method can access its local variables. • a method's local variables cannot be accessed by other methods.

More Related