Objects, Classes, and Interfaces - PowerPoint PPT Presentation

objects classes and interfaces n.
Skip this Video
Loading SlideShow in 5 Seconds..
Objects, Classes, and Interfaces PowerPoint Presentation
Download Presentation
Objects, Classes, and Interfaces

play fullscreen
1 / 112
Objects, Classes, and Interfaces
Download Presentation
Download Presentation

Objects, Classes, and Interfaces

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Objects, Classes, and Interfaces • Creating Objects • Creating Classes • Subclasses, Superclasses, and Inheritance • Creating and Using Interfaces • Creating and Using Packages

  2. The Life Cycle of an Object • Typically, Java programs create many objects from prototypes known as classes. • These objects interact with one another by sending each other messages. • The result of a message is a method invocation which performs some action or modifies the state of the receiving object. • Once an object has completed the work for which it was created, it is garbage collected and its resources recycled for the use of other objects.

  3. Creating Objects • An object is a software module that has state and behavior. • An object's state is contained in its member variables and its behavior is implemented through its methods. • In Java, you create an object by creating an instance of a class or, in other words, instantiating a class

  4. Creating Objects Date today = new Date(); • Date is a class in the java.util package • This single statement actually performs three actions: declaration, instantiation, and initialization • The new operator instantiates the Date class (thereby creating a new Data object), • Date() initializes the object.

  5. Declaring an Object Date today; • In Java, classes and interfaces are just like a data type. • So type can be the name of a class such as the Date class or the name of an interface. • Declarations do not create new objects, just variables named to hold objects. • To instantiate a class, use the new operator. today = new Date();

  6. Instantiating an Object • The new operator instantiates a class by allocating memory for a new object of that type by calling to a constructor method of that class. • Constructor methods are special methods provided by each Java class that are responsible for initializing new objects of that type. • The new operator creates the object, the constructor initializes it.

  7. Instantiating an Object new Rectangle(0, 0, 100, 200); • The new operator returns a reference to the newly created object. • This reference can be assigned to a variable of the appropriate type. rect = new Rectangle(0, 0, 100, 200); • Remember that that a class essentially defines a new reference data type.

  8. Initializing an Object • A class may provide multiple constructors to perform different kinds of initialization on new objects. • They have the same name as the class and have no return type. Date() • A constructor that takes no arguments is known as the default constructor. • Most classes have at least one constructor, the default constructor.

  9. Initializing an Object • If a class has multiple constructors, they all have the same name but different number or type of arguments. • Each constructor initializes the new object in a different way. Date MyBirthday = new Date(1963, 8, 30); • The compiler can differentiate the constructors through the type and numberof the arguments.

  10. Using Objects • Suppose that after creating a new Rectangle, you would like to move it to a different location. • The Rectangle class provides two equivalent ways to move the rectangle: 1. manipulate the object's x, y variables directly 2. call the move() method

  11. Using Objects • It is often considered "more object-oriented" and safer to manipulate an object's variables indirectly through its protective layer of methods. • Manipulating an object's variables directly is often considered error-prone; you could potentially put the object into an inconsistent state. • Java provides a mechanism whereby classes can restrict or allow access to its variables and methods by objects of another type.

  12. Referencing an Object's Variables • To access an object's variables, simply append the variable name to an object reference with an intervening '.' (period). objectReference.variable rect.x = 15; // change x position rect.y = 37; // change y position area = rect.height * rect.width; area = bob.height * bob.width;

  13. Referencing an Object's Variables • Note that the first part of the name of an object's variables (the objectReference in objectReference.variable) must be a reference to an object. • While you can use a variable name here, you can also use any expression that returns an object reference. height = new Rectangle().height;

  14. Calling an Object's Methods • Calling an object's method is similar to getting an object's variable.objectReference.methodName(argumentList); or objectReference.methodName(); rect.move(15, 37); bob.move(244, 47); • Method calls are directed at a specific object; the object specified in the method call is the object that responds to the instruction. • Method calls are also known as messages.

  15. Calling an Object's Methods • A method call is an expression and evaluates to some value. • The value of a method call is its return value, if it has one. if ( rect.inside(mouse.x, mouse.y ) ) { . . . // mouse is in the rectangle . . . } else { . . . // mouse is outside of the rectangle . . . }

  16. Calling an Object's Methods • While you can use a variable name here, you can also use any expression that returns an object reference. new Rectangle(0, 0, 100, 50).equals(anotherRect) • The expression new Rectangle(0, 0, 100, 50) evaluates to an object reference that refers to a Rectangle object.

  17. Cleaning Up Unused Objects • Java saves you from keeping track of all the objects you create in order to destroy them when they are no longer needed. • The Java runtime environment deletes objects when it determines that they are no longer being used. • This process is known as garbage collection.

  18. Cleaning Up Unused Objects • An object is eligible for garbage collection when there are no more references to that object. • References that are held in a variable are naturally dropped when the variable goes out of scope. • Or you can explicitly drop an object reference by setting the value of a variable whose data type is a reference type to null.

  19. The Garbage Collector • The Java runtime environment has a mark-sweep garbage collector that periodically scans Java's dynamic memory areas for objects, marking those that are referenced, and collect objects that are not marked. • The garbage collector runs synchronously when the system runs out of memory or in response to a request from a Java program. • In some systems, Java garbage collector runs asynchronously when the system is idle. • Your Java program can ask the garbage collector to run at any time by calling System.gc().

  20. Finalization • Before an object gets garbage collected, it is given an opportunity to clean up after itself through a call to the object's finalize() method. • This process is known as finalization. • During finalization an object may wish to free system resources such as files and sockets or drop references to other objects so that they in turn become eligible for garbage collection. • The finalize() method is a member of the java.lang.Object class. • A class must override the finalize() method to perform any finalization necessary for objects of that type.

  21. Creating Classes • A class is a blueprint or prototype that you can use to create many objects. • The implementation of a class is comprised of two components: the class declaration and the class body. classDeclaration { classBody }

  22. The Class Declaration • within the class declaration you can: • declare what the class's superclass is • list the interfaces implemented by the class • declare whether the class is public, abstract, or final [ modifiers ] class ClassName [ extends SuperClassName ] [ implements InterfaceNames ] { . . . }

  23. Declaring a Class's Superclass • In Java, every class has a superclass. If you do not specify a superclass for your class, it is assumed to be the Object class (declared in java.lang). • To specify an object's superclass explicitly: class NameOfClass extends SuperClassName { . . . }

  24. Declaring a Class's Superclass • A subclass inherits variables and methods from its superclass. • Creating a subclass can be as simple as including the extends clause in your class declaration. • However, you usually have to make other provisions in your code when subclassing a class, such as overriding methods. class ImaginaryNumber extends Number { . . . }

  25. Listing the Interfaces Implemented by a Class • An interface declares a set of methods and constants without specifying the implementation for any of the methods. • When a class claims to implement an interface, it's claiming to provide implementations for all of the methods declared in the interface. class ImaginaryNumber extends Number implements Arithmetic { . . . }

  26. Listing the Interfaces Implemented by a Class • The class thereby guarantees that it provides implementations for all the methods declared by the interface • If any implementations for methods defined in the interface are missing from the class, the compiler will print an error message and refuse to compile your program: nothing.java:5: class ImaginaryNumber must be declared abstract. It does not define java.lang.Number add(java.lang.Number, java.lang.Number) from interface Arithmetic. class ImaginaryNumber extends Number implements Arithmetic { ^

  27. Listing the Interfaces Implemented by a Class • Note that the method signatures of the methods declared in the interface must match the method signatures of the methods implemented in the class. • Using the final modifier you can declare that your class is final; that is, that your class cannot be subclassed. • There are (at least) two reasons why you might want to do this: security reasons and design reasons. • Note that it doesn't make sense for a class to be both final and abstract. In other words, a class that contains unimplemented methods cannot be final.

  28. Summary of a Class Declaration [ modifiers ] class ClassName [ extends SuperClassName ] [ implements InterfaceNames ] { . . . } • modifiers declare whether the class is public, abstract, or final • ClassName sets the name of the class you are declaring • SuperClassName is the name of ClassName's superclass • InterfaceNames is a comma-delimited list of the interfaces implemented by ClassName

  29. The Class Body • The class body contains declarations for all instance variables and classvariables (known collectively as member variables) for the class. • In addition, the class body contains declarations and implementations for all instancemethods and classmethods (known collectively as methods) for the class.

  30. The Class Body classDeclaration { memberVariableDeclarations methodDeclarations } class TicketOuttaHere { Float price; String destination; Date departureDate; void signMeUp(Float forPrice, String forDest, Date forDate) { price = forPrice; destination = forPrice; departureDate = forDate; } }

  31. Declaring Member Variables • A member variable declaration has two components: the data type of the variable and its name. type variableName; class IntegerClass { int anInteger; . . . // define methods here . . . }

  32. Declaring Member Variables • A member variable and a method can have the same name. For example, the following code is legal: class IntegerClass { int anInteger; int anInteger() { // a method with the same name as a member variable . . . } }

  33. Declaring Member Variables • In short, a member variable declaration looks like this: [accessSpecifier] [static] [final] [transient] [volatile] type variableName • accessSpecifier defines which other classes have access to the variable. • static indicates that the variable is a class member variable as opposed to an instance member variable • final indicates that the variable is a constant • transient variables are not part of the object's persistent state • volatile means that the variable is modified asynchronously

  34. Declaring Constants class Avo { final double AVOGADRO = 6.023e23; } • By convention, names of constant values are spelled in all capital letters. • If your program ever tries to change a constant, the compiler will display an error message similar to the following AvogadroTest.java:5: Can't assign a value to a final variable: AVOGADRO

  35. Declaring Transient Variables • By default member variables are part of the persistent state of the object. • They must be saved when the object is archived. • You use the transient keyword to indicate to the Java virtual machine (JVM) that the indicated variable is not part of the persistent state of the object. class TransientExample { transient int hobo; . . . }

  36. Declaring Volatile Variables • The volatile keyword notifies the Java runtime system that the member variable is modified asynchronously by concurrently running threads. • The volatile variable is loaded from memory before each use, and stored to memory after each use. • This ensures that the value of the variable is consistent and coherent within each thread. class VolatileExample { volatile int counter; . . . }

  37. Implementing Methods • Objects have behavior that is implemented by its methods. • Other objects can ask an object to do something by invoking its methods. • A method implementation consists of two parts: the method declaration and the method body. methodDeclaration { methodBody }

  38. The Method Declaration • Most method attributes can be declared implicitly. • The only two required elements of a method declaration are the method name and the data type returned by the method. class Stack { . . . boolean isEmpty() { . . . } }

  39. Returning a Value from a Method • If a method does not return a value, it must be declared to return void. class Stack { static final int STACK_EMPTY = -1; Object[] stackelements; int topelement = STACK_EMPTY; . . . boolean isEmpty() { if (topelement == STACK_EMPTY) return true; else return false; } }

  40. Returning a Value from a Method • However, the pop() method in the Stack class returns a reference data type: an object. class Stack { static final int STACK_EMPTY = -1; Object[] stackelements; int topelement = STACK_EMPTY; . . . Object pop() { if (topelement == STACK_EMPTY) return null; else { return stackelements[topelement--]; } } }

  41. Returning a Value from a Method • Any method that is not declared void must contain a return statement. • The data type of the value returned by the return statement must match the data type that the method claims to return; • When returning an object, the returned object's data type must be either a subclass of or the exact class indicated. • When returning an interface type, the object returned must implement the specified interface.

  42. A Method's Name • Java supports method name overloading so multiple methods can share the same name. • They are invoked with different signatures (number and type of parameters). class DataRenderer { void draw(String s) { . . . } void draw(int i) { . . . } void draw(float f) { . . . } }

  43. A Method's Name • You should note that overloaded methods must return the same data type. • A class may override a method in its superclass. • The overriding method must have the same name, return type, and parameter list as the method it overrides.

  44. Advanced Method Declaration Features [accessSpecifier] [static] [abstract] [final] [native] [synchronized] returnType methodName ([paramlist]) [throwsexceptionsList] • access specifiers controls whether other objects and classes in your program can call your method. • static specify whether the method is an instance method or a class method. • abstract provides information about itself to subclasses, such as whether the method can be overriden or whether your class even provides an implementation for the method

  45. Advanced Method Declaration Features [accessSpecifier] [static] [abstract] [final] [native] [synchronized] returnType methodName ([paramlist]) [throwsexceptionsList] • If your method throws any exceptions, your method declaration must indicate which exceptions it can throw. • Methods implemented in a language other than Java are called nativemethods and must be declared as such. • You can declare that a method must be synchronized with the synchronized keyword.

  46. Passing Information into a Method • Unlike some other languages, you cannot pass methods into Java methods. • But you could pass an object into a method and then invoke the object's methods. • A method argument can have the same name as one of the class's member variables. If this is the case, then the argument is said to hide the member variable.

  47. Passing Information into a Method • Arguments that hide member variables are often used in constructors to initialize a class class Circle { int x, y, radius; public Circle(int x, int y, int radius) { . . . } }

  48. Passing Information into a Method • Using x, y or radius within the body of the constructor refers to the argument, not to the member variable. • To access the member variable, you must reference it through this--the current object: class Circle { int x, y, radius; public Circle(int x, int y, int radius) { this.x = x; this.y = y; this.radius = radius; } }

  49. Passing Information into a Method • In Java methods, arguments of are passedbyvalue. • When the argument is of primitivetype, pass-by-value means that the method cannot change its value. • When the argument is of referencetype, pass-by-value means that the method cannot change the object reference. • The method can invoke the object's methods and modify the accessible variables within the object.

  50. Passing Information into a Method . . . int r = -1, g = -1, b = -1; pen.getRGBColor(r, g, b); System.out.println("red = " + r + ", green = " + g + ", blue = " + b); . . . class Pen { int redValue, greenValue, blueValue; void getRGBColor(int red, int green, int blue) { // red, green, and blue have been created // and their values are -1 red = redValue; green = greenValue; blue = blueValue; } }