Java i lecture_9_upd1
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
168
On Slideshare
168
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
0
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters
  • White Space Characters

Transcript

  • 1. Java I—Copyright © 2000 Tom Hunter
  • 2. Java I—Copyright © 2000 Tom Hunter Chapter 8 Object-Based Programming
  • 3. Java I—Copyright © 2000 Tom Hunter • How did companies like Dell, Compaq and Gateway get so big? • They bought components from other companies and assembled the pieces into their products. The Genius of Using Objects
  • 4. Java I—Copyright © 2000 Tom Hunter • Dell didn’t design its own motherboards. • Compaq didn’t engineer its own hard drives or operating systems. • They bought the pieces and let somebody else do the engineering. The Genius of Using Objects
  • 5. Java I—Copyright © 2000 Tom Hunter • Dell, Compaq and Gateway let somebody else reinvent the power supply or the motherboard. • Object-Oriented programming is the same idea. • A program is composed of generic objects, with certain standard properties, and certain standard operations the objects can perform. The Genius of Using Objects
  • 6. Java I—Copyright © 2000 Tom Hunter • Dell doesn’t care how the power supply works. • Dell cares if the power supply works. • How the power supply works is hidden and private. • Only the end result is visible. The Genius of Using Objects
  • 7. Java I—Copyright © 2000 Tom Hunter • Dell is only exposed to the end result. • Most important is the power supply’s public face— the power. • Dell doesn’t care how it works internally. The Genius of Using Objects
  • 8. Java I—Copyright © 2000 Tom Hunter • Likewise, in OOP, you only care about what the objects expose. • You can’t know how somebody else’s object works. The Genius of Using Objects
  • 9. Java I—Copyright © 2000 Tom Hunter • You don’t care how the JOptionPane works. • You care about its public methods—its “interface”. You only care about its public methods ! The Genius of Using Objects
  • 10. Java I—Copyright © 2000 Tom Hunter • In traditional procedural programming, you search for verbs in the problem definition. • In procedural programming, the verbs directly suggest procedures and then, lastly, you think of data variables to go with those procedures. The Genius of Using Objects
  • 11. Java I—Copyright © 2000 Tom Hunter • In OOP, you put data structures first, and then look at the algorithms that operate on the data. The Genius of Using Objects
  • 12. Java I—Copyright © 2000 Tom Hunter • The secret to effective OOP: Each object carries out a small set of related tasks. If an object needs a task done—but that task isn’t the job of that object—then that object asks another object to do the task. The Genius of Using Objects “If I can’t do it, then I’ll ask somebody who can.”
  • 13. Java I—Copyright © 2000 Tom Hunter • Again, since the first object can’t do the task, it asks the second object to carry out the task. • In OOP jargon, we say: The Genius of Using Objects “A Client object sends a message to a Server object.”
  • 14. Java I—Copyright © 2000 Tom Hunter • In OOP, one object must never directly manipulate the internal data of another object. • Rather, all communication is through “messages”. (A message is another name for a method call.) The Genius of Using Objects encapsulation
  • 15. Java I—Copyright © 2000 Tom Hunter • When you design your object to hide how it handles requests... (messages / method calls) ...you make it easily reusable. The Genius of Using Objects
  • 16. Java I—Copyright © 2000 Tom Hunter • When you see a Windows OS computer lock up, and you do a CTRL-ALT-DEL, the “Close Program” window that pops up might say: (Not Responding) • That message means that some Windows object is not responding to messages. • Some program called a method, but Windows failed to respond. (No surprise) The Genius of Using Objects
  • 17. Java I—Copyright © 2000 Tom Hunter Class OOP Vocabulary
  • 18. Java I—Copyright © 2000 Tom Hunter class • The term class is the blueprint or recipe from which the object is actually made, or “instantiated.” MyClass boop; boop = new MyClass(); We are now familiar with this: The first “MyClass boop; ” makes a reference called “boop.” OOP Vocabulary
  • 19. Java I—Copyright © 2000 Tom Hunter MyClass boop; At this point, the reference called “boop” does not actually point to any existing object. Soon, it will point to an object of type MyClass, but now the object doesn’t exist. OOP Vocabulary
  • 20. Java I—Copyright © 2000 Tom Hunter MyClass boop = new MyClass(); When this statement executes, the new keyword executes the default Constructor for MyClass, which actually creates an object in memory and assigns that reference to boop. The handle to that just-created object is given to the MyClass reference boop. Now boop points to the new MyClass object. OOP Vocabulary
  • 21. Java I—Copyright © 2000 Tom Hunter state behavior identity
  • 22. Java I—Copyright © 2000 Tom Hunter state behavior identity • Each object in OOP has three key characteristics: What? How? Who? OOP Vocabulary
  • 23. Java I—Copyright © 2000 Tom Hunter state behavior identity • Key characteristics: (What) What is the object’s state? (How) What is the object’s behavior? (Who) What is the object’s identity? OOP Vocabulary
  • 24. Java I—Copyright © 2000 Tom Hunter state behavior identity • All instances of a class have the same instance variables, but of course those variables have different values inside them. • The state—or current values—for an instance of a class, is called the “state” of that class. • The current values of those variables define the current situation or state of this instance of the class. OOP Vocabulary
  • 25. Java I—Copyright © 2000 Tom Hunter state behavior identity • For example, if I have a class called HourlyEmployee, then it contains instance variables: first_name last_name soc_sec_number hourly_rate current_vacation_time OOP Vocabulary
  • 26. Java I—Copyright © 2000 Tom Hunter state behavior identity • All objects that are instances of the same class share the same behavior. • They all have the same methods. • We could send the same messages to all instances of the a class and all would understand and respond to the messages. OOP Vocabulary
  • 27. Java I—Copyright © 2000 Tom Hunter state behavior identity • My class is: HourlyEmployee • All instances of this class have these methods: calculate_pay() setName() getName() setSSN() getSSN() getVacationTime() setVacationTime() getHourlyRate() setHourlyRate() OOP Vocabulary
  • 28. Java I—Copyright © 2000 Tom Hunter state behavior identity • My class is: HourlyEmployee • Every example, or instantiation, of this class has the same methods (behavior) available to it. OOP Vocabulary
  • 29. Java I—Copyright © 2000 Tom Hunter state behavior identity • My class is: HourlyEmployee • Let’s instantiate HourlyEmployee : HourlyEmployee joseph; // empty reference. joseph = new HourlyEmployee(‘Joe’,’Smith’, ’598-22-7893’,’$10.00’,’22.25’); • Now, I have created an instance of the class HourlyEmployee. OOP Vocabulary
  • 30. Java I—Copyright © 2000 Tom Hunter state behavior identity • My class is: HourlyEmployee • I have instantiated HourlyEmployee. • My instance is called joseph. • The identity of my instance is joseph. OOP Vocabulary
  • 31. Java I—Copyright © 2000 Tom Hunter state behavior identity • The identity of my instance is joseph. • The state of my instance is: first_name = ‘Joe’ last_name = ’Smith’ soc_sec_number = ’598-22-7893’ hourly_rate = ’$10.00’ current_vacation_time = ’22.25’ • The behavior of my instance is: calculate_pay() setName() getName() setSSN() getSSN() OOP Vocabulary
  • 32. Java I—Copyright © 2000 Tom Hunter state behavior identity • Now, I will instantiate three objects: HourlyEmployee marie; marie = new HourlyEmployee(‘Mary’,’J.’, ’555-24-1516’,’$30.00’,’0’); HourlyEmployee theodore; theodore = new HourlyEmployee(‘Ted’,’L.’, ’681-22-9875’,’$10.00’,’22’); HourlyEmployee david; david = new HourlyEmployee(‘Dave’,’D.’, ’198-99-0098’,’$15.00’,’8’); OOP VocabularyTell me the identity for each of the three.
  • 33. Java I—Copyright © 2000 Tom Hunter state behavior identity • Identity is the reference to this instantiation. HourlyEmployee marie; marie = new HourlyEmployee(‘Mary’,’J.’, ’555-24-1516’,’$30.00’,’0’); HourlyEmployee theodore; theodore = new HourlyEmployee(‘Ted’,’L.’, ’681-22-9875’,’$10.00’,’22’); HourlyEmployee david; david = new HourlyEmployee(‘Dave’,’D.’, ’198-99-0098’,’$15.00’,’8’); OOP Vocabulary
  • 34. Java I—Copyright © 2000 Tom Hunter state behavior identity HourlyEmployee marie; marie = new HourlyEmployee(‘Mary’,’J.’, ’555-24-1516’,’$30.00’,’0’); HourlyEmployee theodore; theodore = new HourlyEmployee(‘Ted’,’L.’, ’681-22-9875’,’$10.00’,’22’); HourlyEmployee david; david = new HourlyEmployee(‘Dave’,’D.’, ’198-99-0098’,’$15.00’,’8’); OOP VocabularyTell me the behaviors for each of the three.
  • 35. Java I—Copyright © 2000 Tom Hunter state behavior identity • All three have the exact same behaviors. HourlyEmployee marie; marie = new HourlyEmployee(‘Mary’,’J.’, ’555-24-1516’,’$30.00’,’0’); HourlyEmployee theodore; theodore = new HourlyEmployee(‘Ted’,’L.’, ’681-22-9875’,’$10.00’,’22’); HourlyEmployee david; david = new HourlyEmployee(‘Dave’,’D.’, ’198-99-0098’,’$15.00’,’8’); OOP Vocabulary
  • 36. Java I—Copyright © 2000 Tom Hunter state behavior identity HourlyEmployee marie; marie = new HourlyEmployee(‘Mary’,’J.’, ’555-24-1516’,’$30.00’,’0’); HourlyEmployee theodore; theodore = new HourlyEmployee(‘Ted’,’L.’, ’681-22-9875’,’$10.00’,’22’); HourlyEmployee david; david = new HourlyEmployee(‘Dave’,’D.’, ’198-99-0098’,’$15.00’,’8’); OOP VocabularyTell me the state for each of the three.
  • 37. Java I—Copyright © 2000 Tom Hunter state behavior identity • The state of each instance is defined by its instance variables. HourlyEmployee marie; marie = new HourlyEmployee(‘Mary’,’J.’, ’555-24-1516’,’$30.00’,’0’); HourlyEmployee theodore; theodore = new HourlyEmployee(‘Ted’,’L.’, ’681-22-9875’,’$10.00’,’22’); HourlyEmployee david; david = new HourlyEmployee(‘Dave’,’D.’, ’198-99-0098’,’$15.00’,’8’); OOP Vocabulary
  • 38. Java I—Copyright © 2000 Tom Hunter state behavior identity • The state of an instance can only be changed by going through its methods or behaviors. HourlyEmployee marie; marie = new HourlyEmployee(‘Mary’,’J.’, ’555-24-1516’,’$30.00’,’0’); marie.setSSN( ‘444-33-1264’ ); OOP Vocabulary
  • 39. Java I—Copyright © 2000 Tom Hunter Class Scope
  • 40. Java I—Copyright © 2000 Tom Hunter Class Scope • A class’s Instance variables and methods have a thing called “class scope.” • Within the class (within the scope of that class), class member variables are accessible by name. • So, inside or outside of any method in that class, those instance variables can be reached from anywhere in the class. OOP Vocabulary
  • 41. Java I—Copyright © 2000 Tom Hunter Class Scope • If a member variable has been (foolishly) declared public, then it can be accessed outside of the class by simply referencing as follows: ClassName.primitive_variable ClassName.Object_variable. • Another instance of this class has access to the instance variables in any other instance of this class. • You can use the instance identifier or the class name if it is declared as a “static” variable. OOP Vocabulary
  • 42. Java I—Copyright © 2000 Tom Hunter Cosmic Base Class
  • 43. Java I—Copyright © 2000 Tom Hunter Cosmic Base Class • In Java, all classes are built on other classes. • We say, that one class extends another class. • Ultimately, all classes in Java stem from one central “Cosmic Base Class” called Object. • Even if you didn’t use the word “extends” in your class definition, you were still always extending Object by default. OOP Vocabulary
  • 44. Java I—Copyright © 2000 Tom Hunter Base Class • When you extend any “Base Class”, the new (derived) class has all the properties ( instance variables) and methods of its parent, or Base Class. • You can choose to modify or keep any method of the parent, or you can create methods that only apply to the child or “inherited” class. OOP Vocabulary
  • 45. Java I—Copyright © 2000 Tom Hunter Inheritance
  • 46. Java I—Copyright © 2000 Tom Hunter Inheritance • The concept of extending a base class is called “Inheritance.” • Inheritance is the second fundamental concept of Object-Oriented programming. (Encapsulation is the first, Polymorphism is the third) OOP Vocabulary
  • 47. Java I—Copyright © 2000 Tom Hunter Relationships Between Classes • Classes can be related to each other in one of three alternative ways: use containment ( “has-a” ) inheritance ( “is-a” ) OOP Vocabulary
  • 48. Java I—Copyright © 2000 Tom Hunter • When one class sends messages to another class, we say it “uses” the class that receives its messages. Use OOP Vocabulary
  • 49. Java I—Copyright © 2000 Tom Hunter • When one class lives as an Instance Variable within another class, we say it is “Contained”, a “has-a” relationship. Containment ( “has-a” ) OOP Vocabulary
  • 50. Java I—Copyright © 2000 Tom Hunter • When one class inherits from another class, we say it is an “is-a” relationship. inheritance ( “is-a” ) OOP Vocabulary
  • 51. Java I—Copyright © 2000 Tom Hunter Relationships Between Classes: use • Imagine that we have a class Order. • Class Order needs to use the class Account, in order to check for credit status. OOP Vocabulary
  • 52. Java I—Copyright © 2000 Tom Hunter Relationships Between Classes: use • Generally, if a method of class Order sends a message to an object of class Account, then Order uses Account. • In other words, Order uses Account when Order calls methods of Account. OOP Vocabulary Account Order message
  • 53. Java I—Copyright © 2000 Tom Hunter Relationships Between Classes: use • Also, we say class Order uses class Account if: • A method of Order : creates receives or returns objects of class Account . OOP Vocabulary
  • 54. Java I—Copyright © 2000 Tom Hunter Relationships Between Classes: use • Design Tip: Avoid the “use” relationship whenever you can. If you “use” somebody else’s class, then any changes to that class can break your class. OOP Vocabulary
  • 55. Java I—Copyright © 2000 Tom Hunter Relationships Between Classes: containment • The “Containment” relationship (also known as the “Composition” relationship) is a special casespecial case of the “use” relationship. • In a Containment / Composition relationship, at least one method of one class actually contains an object of another class. OOP Vocabulary
  • 56. Java I—Copyright © 2000 Tom Hunter Order Relationships Between Classes: containment ( In the use relationship, it calls methods of another object.) ( In the containment relationship, it contains another object.) OOP Vocabulary Account Order message Account
  • 57. Java I—Copyright © 2000 Tom Hunter Relationships Between Classes: containment • In a “has-a” relationship, a class becomes an instance variable for the class we are defining. OOP Vocabulary public class Order extends Object { Account acct = new Account();
  • 58. Java I—Copyright © 2000 Tom Hunter Relationships Between Classes: inheritance • Inheritance means specialization. • When we inherit from a class, we wish to keep nearly everything in the base class (Superclass). • In inheritance, we seek to elaborate on what we receive from the Superclass. OOP Vocabulary
  • 59. Java I—Copyright © 2000 Tom Hunter Relationships Between Classes: inheritance • We start with the class Order. • Then, we wish to create a Subclass off of Order. • Our Subclass is called RushOrder. OOP Vocabulary
  • 60. Java I—Copyright © 2000 Tom Hunter Relationships Between Classes: inheritance • Class RushOrder has everything that Order has, but it: -adds a few instance variables, maybe -adds a method or two and -overrides a method or two. OOP Vocabulary
  • 61. Java I—Copyright © 2000 Tom Hunter Relationships Between Classes • These three relationships between classes form the foundation of Object-Oriented Design. use “has-a” “is-a” OOP Vocabulary
  • 62. Java I—Copyright © 2000 Tom Hunter Techniques for Using Objects
  • 63. Java I—Copyright © 2000 Tom Hunter Techniques for Using Objects • We have spent a lot of time emphasizing the difference between a reference and the object to which it refers. JLabel howdy; howdy = new JLabel( “How Are Ya?” ); OOP Vocabulary
  • 64. Java I—Copyright © 2000 Tom Hunter howdy “How are Ya?” • We start off by declaring a reference “howdy” to an object of type JLabel. JLabel howdy; • Then, we instantiate the object by calling its constructor with the new keyword, and assign the handle to this instantiation to the reference we declared: “howdy”. JLabel howdy = new JLabel( “How Are Ya?” );
  • 65. Java I—Copyright © 2000 Tom Hunter howdy “How are Ya?” • Okay, what happens when I do the following statement? JLabel hello; // A new reference hello = howdy; howdy = new JLabel( “How Are Ya?” ); hello • Now, both references point to the exact same object. • Any changes made from howdy will be reflected in hello.
  • 66. Java I—Copyright © 2000 Tom Hunter import javax.swing.*; public class JLabelAssign { public static void main( String args[] ) { JLabel howdy, hello; String out1, out2; howdy = new JLabel( "Howdy pardner!" ); hello = new JLabel( "Hello there!" ); out1 = howdy.getText(); out2 = hello.getText(); System.out.println( "Before howdy = " + out1 ); System.out.println( "Before hello = " + out2 ); howdy = hello; out1 = howdy.getText(); out2 = hello.getText(); System.out.println( "After howdy = " + out1 ); System.out.println( "After hello = " + out2 ); howdy.setText( "Yippy Kai Yay!" ); out1 = howdy.getText(); out2 = hello.getText(); System.out.println( ”After Change howdy = " + out1 ); System.out.println( ”Don’t change hello = " + out2 ); System.exit( 0 ); } } Before howdy = Howdy pardner! Before hello = Hello there! After howdy = Hello there! After hello = Hello there! After change howdy = Yippy Kai Yay! Don’t change hello = Yippy Kai Yay! Press any key to continue . . .
  • 67. Java I—Copyright © 2000 Tom Hunter Controlling Access to Methods and Variables
  • 68. Java I—Copyright © 2000 Tom Hunter Controlling Access to Methods: public • public—this lets clients see the services (methods) the class provides (which means view the interface.) —The interface is the collective name for all the various methods that are available in the class. —Methods should be public. OOP Vocabulary
  • 69. Java I—Copyright © 2000 Tom Hunter Controlling Access to Member Variables and Methods: public & private • private—this is the default setting. —It hides implementation details. — Private data members (variables) are only accessible through the public interface (Accessor methods) using public methods. —Only utility methods should be made private. Utility methods are used only within the class. OOP Vocabulary
  • 70. Java I—Copyright © 2000 Tom Hunter Controlling Access to Member: package • package—if you don’t specify that a method or a data variable is either private or public, then when you have automatically given it package access. • If your program has only one class definition—this change is transparent. It has zero effect. H O W E V E R... OOP Vocabulary
  • 71. Java I—Copyright © 2000 Tom Hunter Controlling Access to Member: package • if you don’t specify either public or private for any feature… [ meaning class, method or variable ] can be accessed by all methods in the same package! OOP Vocabulary
  • 72. Java I—Copyright © 2000 Tom Hunter Controlling Access to Member: package • So, if you have the following field in your class: public class MyClass { int mySalary; … } … and your class is stored in java.util.*; then any other method in any class that is also stored in this package can change this variable to anything it wants. No methods needed! OOP Vocabulary
  • 73. Java I—Copyright © 2000 Tom Hunter What’s more, anybody can add their own class to any package. And if they had written a method to exploit that variable with package access, they could do anything they wanted!
  • 74. Java I—Copyright © 2000 Tom Hunter Controlling Access to Member: package • So, if your program uses many classes that are stored in the same package, they can directly access each other’s package-access methods and data variables. • They only need to use the reference.variable to do so. int minute; // minute declared without public // or private. Time2.minute // Other members of its class can // directly access minute. OOP Vocabulary
  • 75. Java I—Copyright © 2000 Tom Hunter Creating a Package • A package is a way to organize classes. • Normally, you create a public class. • If you don’t define your class as public, then it’s only accessible to other classes in the same package. OOP Vocabulary
  • 76. Java I—Copyright © 2000 Tom Hunter Creating a Package: the process • use the keyword package followed by the location. package com.sun.java; • The package statement must be the first statement in your class file. • Compile it in DOS using the -d option javac -d Time2.java OOP Vocabulary
  • 77. Java I—Copyright © 2000 Tom Hunter Final Instance Variables
  • 78. Java I—Copyright © 2000 Tom Hunter Final Instance Variables • The principle of encapsulation is built around the idea of limiting access to variables. • This “least privilege” concept can be expanded to include variables that should never be changed, or “Constants”. • Since this value is a constant, the compiler could optimize by replacing references to that variable with its constant value. • Then there is no need to look up its value when it is referenced. OOP Vocabulary
  • 79. Java I—Copyright © 2000 Tom Hunter Final Instance Variables • If a variable is defined as being “final” then it must be initialized in the same statement. • It can never again be changed. • By custom, it should be declared as all upper case. • Any internal words in the identifier should be separated by underscores. OOP Vocabulary
  • 80. Java I—Copyright © 2000 Tom Hunter Final Instance Variables • If you try to change a variable that you earlier declared as being “final”, then the compiler will complain. • Obviously, it is better to have the compiler complain, than to have your program crash in production. • Whether or not a variable is final is independent of its access. I.e., it can be declared either public or private. private final int NUMBER_OF_MONTHS = 12; final String FIRST_MONTH = “January”; OOP Vocabulary
  • 81. Java I—Copyright © 2000 Tom Hunter Final Methods
  • 82. Java I—Copyright © 2000 Tom Hunter Final Methods • When a method is declared to be final, Java knows that the method can never be overridden. • A final method must be fully defined when it is declared. OOP Vocabulary
  • 83. Java I—Copyright © 2000 Tom Hunter Final Methods • You cannot, for example, have an abstract final method. N E V E R • Since it is final, and can never be overridden by subclasses, the Java compiler can replace the call to the method with inline code if it wants. OOP Vocabulary
  • 84. Java I—Copyright © 2000 Tom Hunter Final Methods • As for security, if you declare a method to be final, then you can be sure it isn’t overridden. • For example, class Object has a method called getClass() that is declared final. • No subclass can override this method and thereby return some other class type to hide its identity. OOP Vocabulary
  • 85. Java I—Copyright © 2000 Tom Hunter Final Classes
  • 86. Java I—Copyright © 2000 Tom Hunter Final Classes • A final class makes all of its methods final as well, since a final class cannot be extended. • Examples of final classes are: Integer, Long, Float and Double. • None of these “wrapper” classes can be subclassed. • String is another class that’s declared final . OOP Vocabulary
  • 87. Java I—Copyright © 2000 Tom Hunter Final Classes • So, if you want to stop programmers from every making a subclass of a particular class, you can declare that class to be final. OOP Vocabulary
  • 88. Java I—Copyright © 2000 Tom Hunter Objects Passed By Reference
  • 89. Java I—Copyright © 2000 Tom Hunter Objects Passed By Reference • As we know the name or reference for an object represents a memory location where the object is stored. • When an object is passed, only the reference is passed. Object-Based Programming
  • 90. Java I—Copyright © 2000 Tom Hunter Objects Passed By Reference • That means, only the address of the object is passed. • A copy is NOT made of the object. • This will have interesting implications. Object-Based Programming
  • 91. Java I—Copyright © 2000 Tom Hunter Creating Our First Class Object
  • 92. Java I—Copyright © 2000 Tom Hunter Creating Our First Class Object • Up until now, our classes have either been Applets or Applications. • Now we create a class that is neither. • This class cannot execute unless it is instantiated by either an Application or an Applet. Object-Based Programming
  • 93. Java I—Copyright © 2000 Tom Hunter Creating Our First Class Object • First we create the class. • Then we create another Applet/Application class to test it. Object-Based Programming
  • 94. Java I—Copyright © 2000 Tom Hunter import java.text.DecimalFormat; public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public Time1() { setTime( 0, 0, 0 ); } public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } We would use this class to display the time, and control how the user changed it.
  • 95. Java I—Copyright © 2000 Tom Hunter import java.text.DecimalFormat; public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public Time1() { setTime( 0, 0, 0 ); } public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } We can only have one public class per file. This class would be stored in a file called “Time1.java.” Question: Does that mean we can include other classes in our file—if they are not declared public?
  • 96. Java I—Copyright © 2000 Tom Hunter import java.text.DecimalFormat; public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public Time1() { setTime( 0, 0, 0 ); } public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } In keeping with encapsulation, the member- access modifiers declare our instance variables private. When this class gets instantiated, the only way to access these variables is through the methods of the class.
  • 97. Java I—Copyright © 2000 Tom Hunter import java.text.DecimalFormat; public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public Time1() { setTime( 0, 0, 0 ); } public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } The Constructor method “ Time1()” must have the same name as the class so the compiler always knows how to initialize the class.
  • 98. Java I—Copyright © 2000 Tom Hunter import java.text.DecimalFormat; public class Time1 extends Object { private int hour; // 0 - 23 private int minute; // 0 - 59 private int second; // 0 - 59 public Time1() { setTime( 0, 0, 0 ); } public void setTime( int h, int m, int s ) { hour = ( ( h >= 0 && h < 24 ) ? h : 0 ); minute = ( ( m >= 0 && m < 60 ) ? m : 0 ); second = ( ( s >= 0 && s < 60 ) ? s : 0 ); } The method setTime()takes in the time arguments. It validates the hours, minutes and seconds to make sure they make sense. Now you can see why the concept of a class might be pretty nifty.
  • 99. Java I—Copyright © 2000 Tom Hunter Different Kinds of Methods
  • 100. Java I—Copyright © 2000 Tom Hunter The different kinds of methods are… Constructor—instantiates the class. Accessor—accesses the member variables in the class. Mutator—(also called Manipulator)—to change or write to the member variables of the class. Utility—private methods that do work for the other methods of the class. ( More Later )
  • 101. Java I—Copyright © 2000 Tom Hunter public String toUniversalString() { DecimalFormat twoDigits = new DecimalFormat( "00" ); return twoDigits.format( hour ) + ":" + twoDigits.format( minute ) + ":" + twoDigits.format( second ); } public String toString() { DecimalFormat twoDigits = new DecimalFormat( "00" ); return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) + ":" + twoDigits.format( minute ) + ":" + twoDigits.format( second ) + ( hour < 12 ? " AM" : " PM" ); } } // end of class Time1 Method toString() originates in class Object. When you want to see what is in the instance variables of the class, you call the toString() method. Every class you create should override this method and create its own copy.
  • 102. Java I—Copyright © 2000 Tom Hunter Using Our New Class • Now we have a new class Time1. • Class Time1 keeps time variables. • The class also validates any time we wish to create. • It prevents us from creating an impossible time.
  • 103. Java I—Copyright © 2000 Tom Hunter Using Our New Class • As of yet, there is no actual object. • Right now, it is only a recipe for an object of our type. • In other words, we haven’t instantiated it yet.
  • 104. Java I—Copyright © 2000 Tom Hunter Using Our New Class • We cannot instantiate it in this class. • We need to create another class to do actually make an example of this class.
  • 105. Java I—Copyright © 2000 Tom Hunter Using Our New Class • We need to create a driver program TimeTest.java • The only purpose of this new class is to instantiate and test our new class Time1.
  • 106. Java I—Copyright © 2000 Tom Hunter import javax.swing.JOptionPane; public class TimeTest { public static void main( String args[] ) { Time1 t = new Time1(); // calls Time1 constructor } } • Now we are using the class Time1 that we just created. • This line creates a reference “t” to an object of type Time1 . • Then, the “new Time1() calls the Constructor method to instantiate our new Time1 object “t”.
  • 107. Java I—Copyright © 2000 Tom Hunter import javax.swing.JOptionPane; public class TimeTest { public static void main( String args[] ) { Time1 t = new Time1(); // calls Time1 constructor String output; output = "The initial universal time is: " + t.toUniversalString() + "nThe initial time is: " + t.toString() + "nImplicit toString() call: " + t; System.exit( 0 ); } } • In this next line, you see how we are calling two different methods of our new class. We’re calling toUniversalString() and toString().
  • 108. Java I—Copyright © 2000 Tom Hunter import javax.swing.JOptionPane; public class TimeTest { public static void main( String args[] ) { Time1 t = new Time1(); // calls Time1 constructor String output; output = "The initial universal time is: " + t.toUniversalString() + "nThe initial time is: " + t.toString() + "nImplicit toString() call: " + t; System.exit( 0 ); } } • One curious thing is this naked reference “ t ” sitting out here by itself. What does that do? • Well, anytime you concatenate an object to a String, you automatically call its toString() method.
  • 109. Java I—Copyright © 2000 Tom Hunter import javax.swing.JOptionPane; public class TimeTest { public static void main( String args[] ) { Time1 t = new Time1(); // calls Time1 constructor String output; output = "The initial universal time is: " + t.toUniversalString() + "nThe initial time is: " + t.toString() + "nImplicit toString() call: " + t; t.setTime( 13, 27, 6 ); output += "nnUniversal time after setTime is: " + t.toUniversalString() + "nStandard time after setTime is: " + t.toString(); t.setTime( 99, 99, 99 ); // all invalid values output += "nnAfter attempting invalid settings: " + "nUniversal time: " + t.toUniversalString() + "nStandard time: " + t.toString(); JOptionPane.showMessageDialog( null, output, Testing Class Time1", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); } }
  • 110. Java I—Copyright © 2000 Tom Hunter Varieties of Methods: details • In the Applications we have created so far, there has only been one method—main. • In the Applets we have created, there have been several standard methods: init(), start() and paint(). • Applets have other standard methods, as we know.
  • 111. Java I—Copyright © 2000 Tom Hunter Varieties of Methods: details • The class we created—Time1—is neither an Application nor an Applet. • Time1 cannot execute unless another program first instantiatesinstantiates it.
  • 112. Java I—Copyright © 2000 Tom Hunter Varieties of Methods • Encapsulating data and the methods used to access that data is the central role of the class in Object Oriented Programming. • With this class, we make the member variables private. • We create methods used to access the member variables.
  • 113. Java I—Copyright © 2000 Tom Hunter Varieties of Methods • There are several different varieties of methods, and each kind has a different sort of job to do. Constructors—public methods used to initialize a class. Accessors—public methods ( gets ) used to read data. Mutators—public methods ( sets ) used to change data. Utility—private methods used to serve the needs of other public methods. Finalizers—protected methods used to do termination housekeeping.
  • 114. Java I—Copyright © 2000 Tom Hunter Varieties of Methods: Constructors • The Constructor is named exactly the same as the class. • The Constructor is called when the new keyword is used. • The Constructor cannot have any return type— not even void.
  • 115. Java I—Copyright © 2000 Tom Hunter Varieties of Methods: Constructors • The Constructor instantiates the object. • It initializes instance variables to acceptable values. • The “default” Constructor accepts no arguments. • The Constructor method is usually overloaded.
  • 116. Java I—Copyright © 2000 Tom Hunter Varieties of Methods: Constructors • The overloaded Constructor usually takes arguments. • That allows the class to be instantiated in a variety of ways. • If the designer neglects to include a constructor, then the compiler creates a default constructor that takes no arguments. • A default constructor will call the Constructor for the class this one extends.
  • 117. Java I—Copyright © 2000 Tom Hunter public Time2() { setTime( 0, 0, 0 ); } • This is the first Constructor. • Notice that it takes no arguments, but it still sets the instance variables for hour, minute and second to consistent initial values of zero.
  • 118. Java I—Copyright © 2000 Tom Hunter public Time2() { setTime( 0, 0, 0 ); } public Time2( int h, int m, int s ) { setTime( h, m, s ); } • These are the first two Constructors. • The second one overrides the first. • The second Constructor takes arguments. • It still calls the setTime() method so it can validate the data.
  • 119. Java I—Copyright © 2000 Tom Hunter public Time2() { setTime( 0, 0, 0 ); } public Time2( int h, int m, int s ) { setTime( h, m, s ); } public Time2( Time2 time ) { setTime( time.hour, time.minute, time.second ); } • This final constructor is quite interesting. • It takes as an argument a Time2 object. • This will make the two Time2 objects equal. Usually, we can’t directly access the private instance variables of an object, because it violates encapsulation. However, objects of the same class are permitted to access each other’s instance variables directly.
  • 120. Java I—Copyright © 2000 Tom Hunter Varieties of Methods: Accessors • Public method to display private variables. • Access to private member variables is provided through the Accessor, or “get” methods. • This allows the designer of the class to control how and anyone can access the private data. • Also called Query methods.
  • 121. Java I—Copyright © 2000 Tom Hunter Varieties of Methods: Mutators • Public methods used to change private variables. • Mutators “set” private data. • The designer can filter he incoming data and ensure it is correct before it is used to change the private data. • This permits the data to be correctly validated before it is used to update the member variables. • Also called Manipulator methods
  • 122. Java I—Copyright © 2000 Tom Hunter The this Reference
  • 123. Java I—Copyright © 2000 Tom Hunter The this Reference • You were sitting in your Ferrarri in your driveway. • Next door, your plumber neighbor was sitting in her Ferrarri. • If you wanted to refer to your neighbor’s Ferrarri, you would naturally say “Jane’s Ferrarri….” • Likewise, it would be perfectly natural for you to refer to the car you were sitting in as “this Ferrarri….”
  • 124. Java I—Copyright © 2000 Tom Hunter The this Reference • “this Ferrarri….” • In Java, the this reference is used to refer to the object you are inside of at this moment. • We say that each object has a reference to itself—called the this reference.
  • 125. Java I—Copyright © 2000 Tom Hunter The this Reference • The this reference is used to refer to both the instance variables and methods of an object. • In Event Handlers, we have used the this reference to show that this Applet (and by implication this Applet’s actionPerformed method) will listen for events from this object. • The this reference can also be used for cascading method calls which allow a reference to be passed back up the calling chain.
  • 126. Java I—Copyright © 2000 Tom Hunter Finalizer Methods
  • 127. Java I—Copyright © 2000 Tom Hunter Finalizer Methods • We know that the Constructor method is used to instantiate and initialize an object in memory. • To avoid the problem called a “memory leak”—one which plagues the C/C++ environment—it is beneficial to have an anti-Constructor method. • Such methods exist. They are called Finalizers, and they control the orderly removal of objects from memory.
  • 128. Java I—Copyright © 2000 Tom Hunter Finalizer Methods • When an object has gone out of scope, the finalizer executes automatically to clean up ( release ) used system resources. • When there are no longer any references to an object, it is eligible for garbage collection. • Garbage Collection is done automatically to return RAM memory back to the system—so called “termination housekeeping.”
  • 129. Java I—Copyright © 2000 Tom Hunter Finalizer Methods • We say that an unused object is marked for garbage collection. • A finalizer method must always be called finalize() • It always takes no arguments and returns void. • The finalize() method is one of the 11 methods inherited from method Object.
  • 130. Java I—Copyright © 2000 Tom Hunter Static Class Members
  • 131. Java I—Copyright © 2000 Tom Hunter Static Class Members • When we instantiate a class, each instantiation of that class gets its own private copies of the instance variables for that class. • However, in certain cases, we would like to have all the instances of the class share one copy of a variable, instead of each having their own copy. interestRate
  • 132. Java I—Copyright © 2000 Tom Hunter Static Class Members • Say we had 30,000 instances of a class called SavingsAccount. • If we changed the interestRate variable they all contained, we would have to make 30,000 method calls to make the change in all of them.
  • 133. Java I—Copyright © 2000 Tom Hunter Static Class Members • However, if we just had defined the interest variable as static, we would have only a single copy that all of them shared. static interestRate • Only the members of the class could access the static variable. • Instance variables that are defined as being static have class scope.
  • 134. Java I—Copyright © 2000 Tom Hunter Static Class Members • If you define your static instance variables as public: public int static interestRate then this variable can be reached by a reference to any object of that class, or through the class name using the dot operator: savacct.interestRate or SavingsAccount.interestRate Or ClassName.staticFieldName;
  • 135. Java I—Copyright © 2000 Tom Hunter Static Class Members • If you define your static instance variables as private: private int static interestRate then the private static instance variables can only be accessed through methods of the class, like any other private variable.
  • 136. Java I—Copyright © 2000 Tom Hunter Static Class Members • Static class members can be accessed even when no instances of that class exist: —To access a public static class member when the class is not instantiated, you tack the name of the class to the name of the variable: SavingsAccount.interestRate Math.PI is a static member variable
  • 137. Java I—Copyright © 2000 Tom Hunter Static Class Members —To access a private static class member when the class is not instantiated, you still prefix with the class name, but then you also use a public static method: SavingsAccount.getInterestRate()
  • 138. Java I—Copyright © 2000 Tom Hunter public class Employee extends Object { private String firstName; private String lastName; private static int count; // # of objects in memory public Employee( String fName, String lName ) { firstName = fName; lastName = lName; ++count; // increment static count of employees System.out.println( "Employee object constructor: " + firstName + " " + lastName ); } protected void finalize() { —count; // decrement static count of employees System.out.println( "Employee object finalizer: " + firstName + " " + lastName + "; count = " + count ); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public static int getCount() { return count; } } Because count is declared as private static, the only way to access its data is by using a public static method.
  • 139. Java I—Copyright © 2000 Tom Hunter public class Employee extends Object { private String firstName; private String lastName; private static int count; // # of objects in memory public Employee( String fName, String lName ) { firstName = fName; lastName = lName; ++count; // increment static count of employees System.out.println( "Employee object constructor: " + firstName + " " + lastName ); } protected void finalize() { —count; // decrement static count of employees System.out.println( "Employee object finalizer: " + firstName + " " + lastName + "; count = " + count ); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public static int getCount() { return count; } }
  • 140. Java I—Copyright © 2000 Tom Hunter Static Class Members —When even a single instance of the class SavingsAccount exists ( is instantiated ), then any of those existing classes can access our static variable ( interestRate) simply by using its name: interestRate
  • 141. Java I—Copyright © 2000 Tom Hunter Static Class Members —When no objects of class SavingsAccount exist, our static variable can still be referenced, but only by going through the Class name and a public static method: SavingsAccount.getInterestRate()
  • 142. Java I—Copyright © 2000 Tom Hunter Static Class Methods
  • 143. Java I—Copyright © 2000 Tom Hunter Static Class Methods • Just like static class members (data variables), static class methods belong to the class—not any one instantiation of the class. • Static class methods do not operate on any instance of a class. • That means you can use them without creating any instance of a class. • For example, all the methods built into the Math class are static methods.
  • 144. Java I—Copyright © 2000 Tom Hunter Static Class Methods • You use this general syntax when using Static Class Methods: ClassName.staticMethod( parameters );
  • 145. Java I—Copyright © 2000 Tom Hunter Static Class Methods I M P O R T A N T • Because static methods do not work with an instance of a class, they can only access static fields. • Let’s think about this: —No instance of the class is instantiated. —In this situation, the only thing that could possibly be present is a static member. —Thus, the only thing that would be around for a static method to see is another static member.
  • 146. Java I—Copyright © 2000 Tom Hunter Static Class Methods • Finally, consider the most famous of all static methods: public static void main( String args[] ) • Since main is static, you don’t need to create an instance of the class in order to call it—and the Java interpreter doesn’t either.
  • 147. Java I—Copyright © 2000 Tom Hunter Static Class Methods • Once again, “static” means: variables and methods that belong to a class but not to any particular object of the class.