Your SlideShare is downloading. ×
0
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Copy of java i lecture_9
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Copy of java i lecture_9

50

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
50
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
1
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 HunterChapter 8Object-Based Programming
    • 3. Java I—Copyright © 2000 Tom Hunter• How did companies like Dell, Compaq andGateway get so big?• They bought components from other companiesand assembled the pieces into their products.The Genius of Using Objects
    • 4. Java I—Copyright © 2000 Tom Hunter• Dell didn’t design its ownmotherboards.• Compaq didn’t engineer its ownhard drives or operating systems.• They bought the pieces and let somebody else dothe engineering.The Genius of Using Objects
    • 5. Java I—Copyright © 2000 Tom Hunter• Dell, Compaq and Gateway let somebody elsereinvent the power supply or the motherboard.• Object-Oriented programming is the same idea.• A program is composed of generic objects, withcertain standard properties, and certain standardoperations 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 theobjects expose.• You can’t know how somebody else’s objectworks.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 itspublic methods !The Genius of Using Objects
    • 10. Java I—Copyright © 2000 Tom Hunter• In traditional procedural programming, yousearch for verbs in the problem definition.• In procedural programming, the verbs directlysuggest procedures and then, lastly, you think ofdata 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 thatoperate 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 taskisn’t the job of that object—then that object asksanother object to do the task.The Genius of Using Objects“If I can’t do it, then I’llask somebody who can.”
    • 13. Java I—Copyright © 2000 Tom Hunter• Again, since the first object can’t do thetask, it asks the second object to carry out thetask.• In OOP jargon, we say:The Genius of Using Objects“A Client object sends amessage to a Server object.”
    • 14. Java I—Copyright © 2000 Tom Hunter• In OOP, one object must never directlymanipulate 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 Objectsencapsulation
    • 15. Java I—Copyright © 2000 Tom Hunter• When you design your object to hide how ithandles 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 “CloseProgram” window that pops up might say:(Not Responding)• That message means that some Windows object isnot responding to messages.• Some program called a method, but Windowsfailed to respond. (No surprise)The Genius of Using Objects
    • 17. Java I—Copyright © 2000 Tom HunterClassOOP Vocabulary
    • 18. Java I—Copyright © 2000 Tom Hunterclass• The term class is the blueprint or recipe fromwhich 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 HunterMyClass boop;At this point, the reference called“boop” does not actually point to anyexisting object.Soon, it will point to an object of typeMyClass, but now the object doesn’t exist.OOP Vocabulary
    • 20. Java I—Copyright © 2000 Tom HunterMyClass boop = new MyClass();When this statement executes, the newkeyword executes the default Constructorfor MyClass, which actually creates an object inmemory and assigns that reference to boop.The handle to that just-created object isgiven to the MyClass reference boop.Now boop points to the new MyClass object.OOP Vocabulary
    • 21. Java I—Copyright © 2000 Tom Hunterstatebehavioridentity
    • 22. Java I—Copyright © 2000 Tom Hunterstatebehavioridentity• Each object in OOP has three key characteristics:What?How?Who?OOP Vocabulary
    • 23. Java I—Copyright © 2000 Tom Hunterstate 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 Hunterstate behavior identity• All instances of a class have the same instancevariables, but of course those variables havedifferent values inside them.• The state—or current values—for an instance of aclass, is called the “state” of that class.• The current values of those variables define thecurrent situation or state of this instance of theclass.OOP Vocabulary
    • 25. Java I—Copyright © 2000 Tom Hunterstate behavior identity• For example, if I have a class calledHourlyEmployee, then it contains instancevariables:first_namelast_namesoc_sec_numberhourly_ratecurrent_vacation_timeOOP Vocabulary
    • 26. Java I—Copyright © 2000 Tom Hunterstate behavior identity• All objects that are instances of the same classshare the same behavior.• They all have the same methods.• We could send the same messages to all instancesof the a class and all would understand and respondto the messages.OOP Vocabulary
    • 27. Java I—Copyright © 2000 Tom Hunterstate 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 Hunterstate behavior identity• My class is: HourlyEmployee• Every example, or instantiation, of this classhas the same methods (behavior) available to it.OOP Vocabulary
    • 29. Java I—Copyright © 2000 Tom Hunterstate 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 classHourlyEmployee.OOP Vocabulary
    • 30. Java I—Copyright © 2000 Tom Hunterstate 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 Hunterstate behavior identity• The identity of my instance isjoseph.• 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 Hunterstate 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 Hunterstate 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 Hunterstate behavior identityHourlyEmployee 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 Hunterstate 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 Hunterstate behavior identityHourlyEmployee 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 Hunterstate behavior identity• The state of each instance is defined by itsinstance 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 Hunterstate behavior identity• The state of an instance can only be changed bygoing 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 HunterClass Scope
    • 40. Java I—Copyright © 2000 Tom HunterClass Scope• A class’s Instance variables and methods havea thing called “class scope.”• Within the class (within the scope of that class), classmember variables are accessible by name.• So, inside or outside of any method in that class, thoseinstance variables can be reached from anywhere in theclass.OOP Vocabulary
    • 41. Java I—Copyright © 2000 Tom HunterClass Scope• If a member variable has been (foolishly) declaredpublic, then it can be accessed outside of the class bysimply referencing as follows:ClassName.primitive_variableClassName.Object_variable.• Another instance of this class has access to theinstance variables in any other instance of this class.• You can use the instance identifier or the class name ifit is declared as a “static” variable.OOP Vocabulary
    • 42. Java I—Copyright © 2000 Tom HunterCosmic Base Class
    • 43. Java I—Copyright © 2000 Tom HunterCosmic 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 onecentral “Cosmic Base Class” called Object.• Even if you didn’t use the word “extends” in yourclass definition, you were still always extendingObject by default.OOP Vocabulary
    • 44. Java I—Copyright © 2000 Tom HunterBase Class• When you extend any “Base Class”, the new(derived) class has all the properties ( instancevariables) and methods of its parent, or Base Class.• You can choose to modify or keep any method ofthe parent, or you can create methods that onlyapply to the child or “inherited” class.OOP Vocabulary
    • 45. Java I—Copyright © 2000 Tom HunterInheritance
    • 46. Java I—Copyright © 2000 Tom HunterInheritance• The concept of extending a base class is called“Inheritance.”• Inheritance is the second fundamental concept ofObject-Oriented programming.(Encapsulation is the first,Polymorphism is the third)OOP Vocabulary
    • 47. Java I—Copyright © 2000 Tom HunterRelationships Between Classes• Classes can be related to each other in one of threealternative ways:usecontainment ( “has-a” )inheritance ( “is-a” )OOP Vocabulary
    • 48. Java I—Copyright © 2000 Tom Hunter• When one class sends messages to another class, we sayit “uses” the class that receives its messages.UseOOP Vocabulary
    • 49. Java I—Copyright © 2000 Tom Hunter• When one class lives as an Instance Variable withinanother 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 isan “is-a” relationship.inheritance ( “is-a” )OOP Vocabulary
    • 51. Java I—Copyright © 2000 Tom HunterRelationships Between Classes: use• Imagine that we have a class Order.• Class Order needs to use the class Account, in orderto check for credit status.OOP Vocabulary
    • 52. Java I—Copyright © 2000 Tom HunterRelationships Between Classes: use• Generally, if a method of class Ordersends a message to an object of class Account,then Order uses Account.• In other words, Order uses Account whenOrder calls methods of Account.OOP VocabularyAccountOrder message
    • 53. Java I—Copyright © 2000 Tom HunterRelationships Between Classes: use• Also, we say class Order uses class Account if:• A method of Order :createsreceives orreturnsobjects of class Account .OOP Vocabulary
    • 54. Java I—Copyright © 2000 Tom HunterRelationships Between Classes: use• Design Tip:Avoid the “use” relationship wheneveryou can. If you “use” somebody else’s class,then any changes to that class can break yourclass.OOP Vocabulary
    • 55. Java I—Copyright © 2000 Tom HunterRelationships 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 anobject of another class.OOP Vocabulary
    • 56. Java I—Copyright © 2000 Tom HunterOrderRelationships Between Classes: containment( In the use relationship, it calls methods of another object.)( In the containment relationship, it contains another object.)OOP VocabularyAccountOrder messageAccount
    • 57. Java I—Copyright © 2000 Tom HunterRelationships Between Classes: containment• In a “has-a” relationship, a class becomes aninstance variable for the class we are defining.OOP Vocabularypublic class Order extends Object{Account acct = new Account();
    • 58. Java I—Copyright © 2000 Tom HunterRelationships Between Classes: inheritance• Inheritance means specialization.• When we inherit from a class, we wish to keep nearlyeverything in the base class (Superclass).• In inheritance, we seek to elaborate on what we receivefrom the Superclass.OOP Vocabulary
    • 59. Java I—Copyright © 2000 Tom HunterRelationships 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 HunterRelationships 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 HunterRelationships Between Classes• These three relationships between classes form thefoundation of Object-Oriented Design.use“has-a”“is-a”OOP Vocabulary
    • 62. Java I—Copyright © 2000 Tom HunterTechniquesforUsing Objects
    • 63. Java I—Copyright © 2000 Tom HunterTechniques for Using Objects• We have spent a lot of time emphasizing the differencebetween 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 Hunterhowdy“How are Ya?”• We start off by declaring a reference “howdy” to an objectof type JLabel.JLabel howdy;• Then, we instantiate the object by calling its constructorwith the new keyword, and assign the handle to thisinstantiation to the reference we declared: “howdy”.JLabel howdy = new JLabel( “How Are Ya?” );
    • 65. Java I—Copyright © 2000 Tom Hunterhowdy“How are Ya?”• Okay, what happens when I do the following statement?JLabel hello; // A new referencehello = 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 Hunterimport 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 HunterControllingAccesstoMethods and Variables
    • 68. Java I—Copyright © 2000 Tom HunterControlling Access to Methods: public• public—this lets clients see the services (methods) theclass provides (which means view the interface.)—The interface is the collective name for all thevarious methods that are available in the class.—Methods should be public.OOP Vocabulary
    • 69. Java I—Copyright © 2000 Tom HunterControlling Access to Member Variables andMethods: public & private• private—this is the default setting.—It hides implementation details.— Private data members (variables) are only accessiblethrough 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 HunterControlling Access to Member: package• package—if you don’t specify that a method or adata variable is either private or public, thenwhen you have automatically given itpackage access.• If your program has only one class definition—thischange is transparent. It has zero effect.H O W E V E R...OOP Vocabulary
    • 71. Java I—Copyright © 2000 Tom HunterControlling Access to Member: package• if you don’t specify either public or private for anyfeature…[ meaning class, method or variable ]can be accessed by all methods in thesame package!OOP Vocabulary
    • 72. Java I—Copyright © 2000 Tom HunterControlling 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 alsostored in this package can change this variableto anything it wants. No methods needed!OOP Vocabulary
    • 73. Java I—Copyright © 2000 Tom HunterWhat’s more, anybody can addtheir own class to anypackage. And if they hadwritten a method to exploitthat variable with packageaccess, they could do anythingthey wanted!
    • 74. Java I—Copyright © 2000 Tom HunterControlling Access to Member: package• So, if your program uses many classes that are storedin the same package, they can directly accesseach other’s package-access methods and datavariables.• They only need to use the reference.variableto 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 HunterCreating 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 onlyaccessible to other classes in the same package.OOP Vocabulary
    • 76. Java I—Copyright © 2000 Tom HunterCreating 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 yourclass file.• Compile it in DOS using the -d optionjavac -d Time2.javaOOP Vocabulary
    • 77. Java I—Copyright © 2000 Tom HunterFinal InstanceVariables
    • 78. Java I—Copyright © 2000 Tom HunterFinal Instance Variables• The principle of encapsulation is built around the idea oflimiting access to variables.• This “least privilege” concept can be expanded to includevariables that should never be changed, or “Constants”.• Since this value is a constant, the compiler could optimizeby replacing references to that variable with its constantvalue.• Then there is no need to look up its value when it isreferenced.OOP Vocabulary
    • 79. Java I—Copyright © 2000 Tom HunterFinal Instance Variables• If a variable is defined as being “final” then it must beinitialized 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 byunderscores.OOP Vocabulary
    • 80. Java I—Copyright © 2000 Tom HunterFinal Instance Variables• If you try to change a variable that you earlier declared asbeing “final”, then the compiler will complain.• Obviously, it is better to have the compiler complain, thanto have your program crash in production.• Whether or not a variable is final is independent of itsaccess. 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 HunterFinal Methods
    • 82. Java I—Copyright © 2000 Tom HunterFinal Methods• When a method is declared to be final, Java knows thatthe method can never be overridden.• A final method must be fully defined when it isdeclared.OOP Vocabulary
    • 83. Java I—Copyright © 2000 Tom HunterFinal Methods• You cannot, for example, have an abstract finalmethod. 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 withinline code if it wants.OOP Vocabulary
    • 84. Java I—Copyright © 2000 Tom HunterFinal 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 calledgetClass() that is declared final.• No subclass can override this method and thereby returnsome other class type to hide its identity.OOP Vocabulary
    • 85. Java I—Copyright © 2000 Tom HunterFinal Classes
    • 86. Java I—Copyright © 2000 Tom HunterFinal 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 HunterFinal Classes• So, if you want to stop programmers from every makinga subclass of a particular class, you can declare that classto be final.OOP Vocabulary
    • 88. Java I—Copyright © 2000 Tom HunterObjects Passed ByReference
    • 89. Java I—Copyright © 2000 Tom HunterObjects Passed By Reference• As we know the name or reference for an objectrepresents a memory locationwhere the object is stored.• When an object is passed, only the reference is passed.Object-Based Programming
    • 90. Java I—Copyright © 2000 Tom HunterObjects 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 HunterCreating OurFirstClass Object
    • 92. Java I—Copyright © 2000 Tom HunterCreating Our First Class Object• Up until now, our classes have either beenApplets or Applications.• Now we create a class that is neither.• This class cannot execute unless it is instantiated by eitheran Application or an Applet.Object-Based Programming
    • 93. Java I—Copyright © 2000 Tom HunterCreating Our First Class Object• First we create the class.• Then we create another Applet/Applicationclass to test it.Object-Based Programming
    • 94. Java I—Copyright © 2000 Tom Hunterimport java.text.DecimalFormat;public class Time1 extends Object{private int hour; // 0 - 23private int minute; // 0 - 59private int second; // 0 - 59public 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 todisplay the time, and controlhow the user changed it.
    • 95. Java I—Copyright © 2000 Tom Hunterimport java.text.DecimalFormat;public class Time1 extends Object{private int hour; // 0 - 23private int minute; // 0 - 59private int second; // 0 - 59public 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 inour file—if they are not declared public?
    • 96. Java I—Copyright © 2000 Tom Hunterimport java.text.DecimalFormat;public class Time1 extends Object{private int hour; // 0 - 23private int minute; // 0 - 59private int second; // 0 - 59public 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 variablesprivate.When this class gets instantiated, the only wayto access these variables is through the methodsof the class.
    • 97. Java I—Copyright © 2000 Tom Hunterimport java.text.DecimalFormat;public class Time1 extends Object{private int hour; // 0 - 23private int minute; // 0 - 59private int second; // 0 - 59public 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 Constructormethod “ Time1()”must have the samename as the class sothe compiler alwaysknows how to initializethe class.
    • 98. Java I—Copyright © 2000 Tom Hunterimport java.text.DecimalFormat;public class Time1 extends Object{private int hour; // 0 - 23private int minute; // 0 - 59private int second; // 0 - 59public 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. Itvalidates the hours, minutes and seconds to make sure theymake sense. Now you can see why the concept of a classmight be pretty nifty.
    • 99. Java I—Copyright © 2000 Tom HunterDifferent Kindsof Methods
    • 100. Java I—Copyright © 2000 Tom HunterThe different kinds of methods are…Constructor—instantiates the class.Accessor—accesses the member variables in the class.Mutator—(also called Manipulator)—to change or writeto the member variables of the class.Utility—private methods that do work for the othermethods of the class.( More Later )
    • 101. Java I—Copyright © 2000 Tom Hunterpublic 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 Time1Method toString() originates in class Object. Whenyou want to see what is in the instance variables of theclass, you call the toString() method. Every classyou create should override this method and create its owncopy.
    • 102. Java I—Copyright © 2000 Tom HunterUsing 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 HunterUsing 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 HunterUsing Our New Class• We cannot instantiate it in this class.• We need to create another class to do actually make anexample of this class.
    • 105. Java I—Copyright © 2000 Tom HunterUsing Our New Class• We need to create a driver program TimeTest.java• The only purpose of this new class is to instantiate andtest our new class Time1.
    • 106. Java I—Copyright © 2000 Tom Hunterimport 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 typeTime1 .• Then, the “new Time1() calls the Constructormethod to instantiate our new Time1 object “t”.
    • 107. Java I—Copyright © 2000 Tom Hunterimport javax.swing.JOptionPane;public class TimeTest{public static void main( String args[] ){Time1 t = new Time1(); // calls Time1 constructorString 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 twodifferent methods of our new class. We’re callingtoUniversalString() andtoString().
    • 108. Java I—Copyright © 2000 Tom Hunterimport javax.swing.JOptionPane;public class TimeTest{public static void main( String args[] ){Time1 t = new Time1(); // calls Time1 constructorString 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 ” sittingout 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 Hunterimport javax.swing.JOptionPane;public class TimeTest{public static void main( String args[] ){Time1 t = new Time1(); // calls Time1 constructorString 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 valuesoutput += "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 HunterVarieties of Methods: details• In the Applications we have created so far, there hasonly been one method—main.• In the Applets we have created, there have been severalstandard methods:init(),start() andpaint().• Applets have other standard methods, as we know.
    • 111. Java I—Copyright © 2000 Tom HunterVarieties of Methods: details• The class we created—Time1—is neither anApplication nor an Applet.• Time1 cannot execute unless anotherprogram first instantiatesinstantiates it.
    • 112. Java I—Copyright © 2000 Tom HunterVarieties of Methods• Encapsulating data and the methods used to access thatdata is the central role of the class in Object OrientedProgramming.• With this class, we make the member variables private.• We create methods used to access the member variables.
    • 113. Java I—Copyright © 2000 Tom HunterVarieties of Methods• There are several different varieties of methods, andeach 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 otherpublic methods.Finalizers—protected methods used to do terminationhousekeeping.
    • 114. Java I—Copyright © 2000 Tom HunterVarieties of Methods: Constructors• The Constructor is named exactly the same asthe class.• The Constructor is called when the newkeyword is used.• The Constructor cannot have any return type—not even void.
    • 115. Java I—Copyright © 2000 Tom HunterVarieties 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 HunterVarieties of Methods: Constructors• The overloaded Constructor usually takes arguments.• That allows the class to be instantiated in a variety ofways.• If the designer neglects to include a constructor, then thecompiler creates a default constructor that takes noarguments.• A default constructor will call the Constructor for theclass this one extends.
    • 117. Java I—Copyright © 2000 Tom Hunterpublic Time2(){setTime( 0, 0, 0 );}• This is the first Constructor.• Notice that it takes no arguments, but it still sets theinstance variables for hour, minute and second toconsistent initial values of zero.
    • 118. Java I—Copyright © 2000 Tom Hunterpublic 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 validatethe data.
    • 119. Java I—Copyright © 2000 Tom Hunterpublic 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 instancevariables of an object, because it violates encapsulation.However, objects of the same class are permitted to accesseach other’s instance variables directly.
    • 120. Java I—Copyright © 2000 Tom HunterVarieties of Methods: Accessors• Public method to display private variables.• Access to private member variables is provided throughthe Accessor, or “get” methods.• This allows the designer of the class to control how andanyone can access the private data.• Also called Query methods.
    • 121. Java I—Copyright © 2000 Tom HunterVarieties of Methods: Mutators• Public methods used to change private variables.• Mutators “set” private data.• The designer can filter he incoming data and ensure it iscorrect before it is used to change the private data.• This permits the data to be correctly validated before itis used to update the member variables.• Also called Manipulator methods
    • 122. Java I—Copyright © 2000 Tom HunterThe thisReference
    • 123. Java I—Copyright © 2000 Tom HunterThe this Reference• You were sitting in your Ferrarri in your driveway.• Next door, your plumber neighbor was sitting in herFerrarri.• If you wanted to refer to your neighbor’s Ferrarri, youwould naturally say “Jane’s Ferrarri….”• Likewise, it would be perfectly natural for you to referto the car you were sitting in as “this Ferrarri….”
    • 124. Java I—Copyright © 2000 Tom HunterThe this Reference• “this Ferrarri….”• In Java, the this reference is used to refer to the objectyou are inside of at this moment.• We say that each object has a reference to itself—calledthe this reference.
    • 125. Java I—Copyright © 2000 Tom HunterThe this Reference• The this reference is used to refer to both the instancevariables and methods of an object.• In Event Handlers, we have used the this reference toshow that this Applet (and by implication thisApplet’s actionPerformed method) will listen forevents from this object.• The this reference can also be used for cascadingmethod calls which allow a reference to be passed backup the calling chain.
    • 126. Java I—Copyright © 2000 Tom HunterFinalizerMethods
    • 127. Java I—Copyright © 2000 Tom HunterFinalizer Methods• We know that the Constructor method is used toinstantiate and initialize an object in memory.• To avoid the problem called a “memory leak”—onewhich plagues the C/C++ environment—it is beneficial tohave an anti-Constructor method.• Such methods exist. They are called Finalizers, and theycontrol the orderly removal of objects from memory.
    • 128. Java I—Copyright © 2000 Tom HunterFinalizer Methods• When an object has gone out of scope, the finalizerexecutes automatically to clean up ( release ) used systemresources.• When there are no longer any references to an object, itis eligible for garbage collection.• Garbage Collection is done automatically to returnRAM memory back to the system—so called“termination housekeeping.”
    • 129. Java I—Copyright © 2000 Tom HunterFinalizer Methods• We say that an unused object is marked for garbagecollection.• A finalizer method must always be calledfinalize()• It always takes no arguments and returns void.• The finalize() method is one of the 11 methodsinherited from method Object.
    • 130. Java I—Copyright © 2000 Tom HunterStatic ClassMembers
    • 131. Java I—Copyright © 2000 Tom HunterStatic Class Members• When we instantiate a class, each instantiation of thatclass gets its own private copies of the instance variablesfor that class.• However, in certain cases, we would like to have all theinstances of the class share one copy of a variable, insteadof each having their own copy.interestRate
    • 132. Java I—Copyright © 2000 Tom HunterStatic Class Members• Say we had 30,000 instances of a class calledSavingsAccount.• If we changed the interestRate variable they allcontained, we would have to make 30,000 method calls tomake the change in all of them.
    • 133. Java I—Copyright © 2000 Tom HunterStatic Class Members• However, if we just had defined the interest variable asstatic, we would have only a single copy that all of themshared.static interestRate• Only the members of the class could access the staticvariable.• Instance variables that are defined as being statichave class scope.
    • 134. Java I—Copyright © 2000 Tom HunterStatic Class Members• If you define your static instance variables as public:public int static interestRatethen this variable can be reached by a reference to anyobject of that class, or through the class name using thedot operator:savacct.interestRate orSavingsAccount.interestRateOrClassName.staticFieldName;
    • 135. Java I—Copyright © 2000 Tom HunterStatic Class Members• If you define your static instance variables as private:private int static interestRatethen the private static instance variables can only beaccessed through methods of the class, like any otherprivate variable.
    • 136. Java I—Copyright © 2000 Tom HunterStatic Class Members• Static class members can be accessed even when noinstances of that class exist:—To access a public static class member when the classis not instantiated, you tack the name of the class to thename of the variable:SavingsAccount.interestRateMath.PI is a static member variable
    • 137. Java I—Copyright © 2000 Tom HunterStatic Class Members—To access a private static class member when the classis 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 Hunterpublic class Employee extends Object{ private String firstName;private String lastName;private static int count; // # of objects in memorypublic Employee( String fName, String lName ){ firstName = fName;lastName = lName;++count; // increment static count of employeesSystem.out.println( "Employee object constructor: " +firstName + " " + lastName );}protected void finalize(){ —count; // decrement static count of employeesSystem.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 declaredas private static, theonly way to access its data isby using a publicstatic method.
    • 139. Java I—Copyright © 2000 Tom Hunterpublic class Employee extends Object{ private String firstName;private String lastName;private static int count; // # of objects in memorypublic Employee( String fName, String lName ){ firstName = fName;lastName = lName;++count; // increment static count of employeesSystem.out.println( "Employee object constructor: " +firstName + " " + lastName );}protected void finalize(){ —count; // decrement static count of employeesSystem.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 HunterStatic Class Members—When even a single instance of the classSavingsAccount exists ( is instantiated ), then any ofthose existing classes can access our static variable( interestRate) simply by using its name:interestRate
    • 141. Java I—Copyright © 2000 Tom HunterStatic Class Members—When no objects of class SavingsAccount exist,our static variable can still be referenced, but only bygoing through the Class name and a public static method:SavingsAccount.getInterestRate()
    • 142. Java I—Copyright © 2000 Tom HunterStatic ClassMethods
    • 143. Java I—Copyright © 2000 Tom HunterStatic Class Methods• Just like static class members (data variables), staticclass methods belong to the class—not any oneinstantiation of the class.• Static class methods do not operate on any instance of aclass.• That means you can use them without creating anyinstance of a class.• For example, all the methods built into the Math classare static methods.
    • 144. Java I—Copyright © 2000 Tom HunterStatic Class Methods• You use this general syntax when using Static ClassMethods:ClassName.staticMethod( parameters );
    • 145. Java I—Copyright © 2000 Tom HunterStatic Class MethodsI M P O R T A N T• Because static methods do not work with an instance ofa 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 couldpossibly be present is a static member.—Thus, the only thing that would be around for astatic method to see is another static member.
    • 146. Java I—Copyright © 2000 Tom HunterStatic Class Methods• Finally, consider the most famous of all staticmethods:public static void main( String args[] )• Since main is static, you don’t need to create an instanceof the class in order to call it—and the Java interpreterdoesn’t either.
    • 147. Java I—Copyright © 2000 Tom HunterStatic Class Methods• Once again, “static” means:variables andmethodsthat belong to a class but not to any particular object ofthe class.

    ×