Your SlideShare is downloading. ×

Oop i

313

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
313
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
23
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
  • 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
  • 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 9Object-Oriented Programming:Part I
    • 3. Java I--Copyright © 2000 Tom HunterSuperclassesandSubclasses
    • 4. Java I--Copyright © 2000 Tom Hunter• So far I this course we have covered two of theBig Three principles of Object-OrientedProgramming:1.) Encapsulation—completely covered2.) Inheritance—briefly covered3.) Polymorphism—still to come.Superclasses and Subclasses
    • 5. Java I--Copyright © 2000 Tom Hunter• As we know, in Inheritance we stand onthe shoulders of earlier work.• We receive all the methods and variablesof an earlier class.Superclasses and Subclasses
    • 6. Java I--Copyright © 2000 Tom Hunter• Polymorphism lets us write programs in ageneral way.• Although we write the programs in ageneral way, the objects themselves causethe behavior to be specific.Superclasses and Subclasses
    • 7. Java I--Copyright © 2000 Tom Hunter• This lets us write programs that will workcorrectly even for objects that haven’t beeninvented yet.Superclasses and Subclasses
    • 8. Java I--Copyright © 2000 Tom HunterInheritance
    • 9. Java I--Copyright © 2000 Tom Hunter• We have already been using the termsSuperclass and Subclass.• A Superclass is the parent class.• A Subclass is the child class.• A Subclass inherits the behavior andvariables of the Superclass.Superclasses and Subclasses: Inheritance
    • 10. Java I--Copyright © 2000 Tom Hunter• A Subclass inherits all the methods and allthe encapsulated data variables of itsDirect Superclass.(the Superclass immediately above a Subclass iscalled its Direct Superclass.)Superclasses and Subclasses
    • 11. Java I--Copyright © 2000 Tom HunterClass JOptionPane inherits from classJComponent.So that means JOptionPane inherits all themethods and all the encapsulated data variables thatlie within JComponent.
    • 12. Java I--Copyright © 2000 Tom Hunter• JComponent is the Superclass• JOptionPane is the SubclassSuperclasses and Subclasses: Inheritance
    • 13. Java I--Copyright © 2000 Tom Hunter• Correct. So, that tells us JComponent inheritsall the methods and all the encapsulated datavariables of Container .• Container is the Superclass.Superclasses and Subclasses: Inheritance• But wait asecond. Isn’tJComponentthe Subclass ofContainer?
    • 14. Java I--Copyright © 2000 Tom Hunter• So, when JOptionPane inherits everything fromJComponent (which itself inherited everything fromContainer), that must mean JOptionPane inheritseverything from both JComponent and Container.Is that true?Superclasses and Subclasses: InheritanceYes
    • 15. Java I--Copyright © 2000 Tom Hunter• So, let’s put this together: theJOptionPane inherits all the methodsand all the encapsulated data variables in…ALL THE SUPERCLASSES ABOVE IT!Superclasses and SubclassesHow could it do that?
    • 16. Java I--Copyright © 2000 Tom Hunter• How?When we want to create a copy of some object,what do we do?Superclasses and Subclasses• Answer:We use the new keyword to fire off the Subclassobject’s Constructor . We instantiate the object.• And so, if we want to create a copy of theSuperSuperclass, we need to...Somehow, fire off the SuperSuperclass object’sConstructor.
    • 17. Java I--Copyright © 2000 Tom Hunter• Whenever you extended another class,(a Superclass) you have created an instance ofevery class above your classevery class above your class in the class hierarchy.• When the Constructor for Sales fires, it silentlyalso fires the Constructors for JApplet and everyother class above JApplet in the hierarchy.Superclasses and Subclassespublic class Sales extends JApplet{...}
    • 18. Java I--Copyright © 2000 Tom Hunter• The Subclass adds to what it inherits from theSuperclass.• Because we say it adds, that implies it alreadyhas everything else!• By the time your Subclass is created, it alreadyhas an instance of every Superclass above it andevery single thing the Superclasses contain!!!!!Superclasses and Subclasses
    • 19. Java I--Copyright © 2000 Tom Hunter• Every method, every data variable present in theSuperclass is also present in the Subclass.• Make sure you understand this:If my class has everything above it—then I can say it isis an example ofthe classes above it.Superclasses and Subclasses
    • 20. Java I--Copyright © 2000 Tom Hunter• Finally, since the Subclass has everything theSuperclass has, we can say:Superclasses and Subclasses“Every Subclass is also anobject of the Superclass.”
    • 21. Java I--Copyright © 2000 Tom Hunter• I’m a resident of Omaha, with everything thatimplies.Superclasses and Subclasses: an Analogy• But, at the same time I’m an Omahan, I’m also aresident of Nebraska.• When I become a resident of Omaha, I inheriteverything it means to be a Nebraskan.• Likewise, when I moved from Russia to Omaha,I not only became an Omahan, I also became aNebraskan and a United States resident.
    • 22. Java I--Copyright © 2000 Tom Hunter• So, let’s ponder this:JOptionPane inherits from JComponent.• The JOptionPane inherits everythingJComponent possesses.Superclasses and Subclasses
    • 23. Java I--Copyright © 2000 Tom Hunter• So, we can say—at the same timeJOptionPane is a JComponent.JOptionPane is a Container.JOptionPane is a Component.JOptionPane is an Object.Superclasses and Subclasses
    • 24. Java I--Copyright © 2000 Tom Hunter• ClassesObject,Component andContainerareIndirect Superclassesto the JOptionPane.Superclasses and Subclasses• JComponent is theDirect Superclass to the JOptionPane.
    • 25. Java I--Copyright © 2000 Tom Hunter• We say JOptionPane is a JComponent, is aContainer, is a Component, is an Object.Superclasses and SubclassesObjectComponentContainerJComponentJOptionPaneThis little arrowpointing upwardsindicates this is an“is a”relationship.
    • 26. Java I--Copyright © 2000 Tom HunterImpact onAccessModifiers
    • 27. Java I--Copyright © 2000 Tom HunterImpact on Access Modifiers• Access Modifiers are among the thorniest andmost confusing aspects of OOP.• But, remember, encapsulation is one of theprimary benefits of object orientation, so access isimportant.Superclasses and Subclasses
    • 28. Java I--Copyright © 2000 Tom HunterImpact on Access Modifiers• The familiar private access modifier lets usshield our instance variables from the prying eyesof the outside world.• Relying on Access Modifiers, you can shield bothyour class’s private instance variables and itsprivate methods.Superclasses and Subclasses
    • 29. Java I--Copyright © 2000 Tom HunterImpact on Access Modifiers• With those ends in mind, Java lets review the fourdifferent levels of access:private,protected,publicand the default if you don’t specify package.Superclasses and Subclasses
    • 30. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• A summary of the various types of accessmodifier:Specifier class subclass package worldprivate Xpackage X Xprotected X X Xpublic X X X X
    • 31. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• As you can see, a class always has access to itsown instance variables, with any access modifier.Specifier class subclass package worldprivate Xpackage X Xprotected X X Xpublic X X X X
    • 32. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• The second column shows that Subclasses of thisclass (no matter what package they are in) haveaccess to public (obviously) and protected variables.Specifier class subclass package worldprivate Xpackage X Xprotected X X Xpublic X X X X
    • 33. Java I--Copyright © 2000 Tom Hunter• Therefore, the important point?Subclasses cancan reach protected-access variables,but can’tcan’t reach package-access variables…unless the Subclasses happen to be saved in thesame package.
    • 34. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• The third column “package” shows that classes inthe same package as the class (regardless of theirparentage) have access to data variables.Specifier class subclass package worldprivate Xpackage X Xprotected X X Xpublic X X X X
    • 35. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• In the fourth column, we see that anything andanyone has access to a public data variable ormethod—defeating the purpose of encapsulation.Specifier class subclass package worldprivate Xpackage X Xprotected X X Xpublic X X X X
    • 36. Java I--Copyright © 2000 Tom Hunterprivate
    • 37. Java I--Copyright © 2000 Tom HunterImpact on Access Modifiers: private• When my class inherits from a Superclass, Icannot access the Superclass’s private datavariables. Private data is Secret!• In other words, the Subclass cannot automaticallyreach the private data variables of the Superclass.• A private data variable is accessible only to theclass in which it is defined.Superclasses and Subclasses
    • 38. Java I--Copyright © 2000 Tom HunterObjects of type Alpha can inspect or modify theiamprivate variable and can call privateMethod,but objects of any other type cannot.class Alpha{private int iamprivate;public Alpha( int iam ){iamprivate = iam;}private void privateMethod(){iamprivate = 2;System.out.println(“” + iamprivate);}}
    • 39. Java I--Copyright © 2000 Tom HunterThe Beta class, for example, cannot access theiamprivate variable or invoke privateMethod on anobject of type Alpha because Beta is not of type Alpha .class Beta{public void accessMethod(){Alpha a = new Alpha();a.iamprivate = 10; // Invalida.privateMethod(); // Invalid}}• The compiler would complain if you tried this.
    • 40. Java I--Copyright © 2000 Tom HunterCan one instance of an Alpha object access theprivate data variables of another instance of anAlpha object?Objects of the same type have access to oneanother’s private members.Yes!
    • 41. Java I--Copyright © 2000 Tom Hunterpackage
    • 42. Java I--Copyright © 2000 Tom HunterVarieties of Access Modifiers: package• If you do not specify the access for either amethod or an encapsulated data variable, then it isgiven the default access:packageSuperclasses and Subclasses
    • 43. Java I--Copyright © 2000 Tom HunterVarieties of Access Modifiers: package• This access allows other classes in the samepackage as your class to access its data variables asif they were their own.package• This level of access assumes that classes in thesame package as your class are friends who won’tharm your class’ data.Superclasses and Subclasses
    • 44. Java I--Copyright © 2000 Tom Hunterpackage Greek;class Delta{int iamprivate;void privateMethod(){System.out.println(“privateMethod”);}}• Notice that no access modifier is declared.So, iamprivate and method privateMethodboth default to package access.• All classes declared in the package Greek, alongwith class Delta, have access to iamprivate andprivateMethod.
    • 45. Java I--Copyright © 2000 Tom HunterVarieties of Access Modifiers: packagepackage• If you use multiple objects from the samepackage, they can access each other’s package-access methods and data variables directly, merelyby referencing an object that has been instantiated.Superclasses and Subclasses
    • 46. Java I--Copyright © 2000 Tom HunterVarieties of Access Modifiers: packagepackage• With package access, other objects in the packagedon’t have to bother going through the methods.They can get right to the variables.Superclasses and Subclasses
    • 47. Java I--Copyright © 2000 Tom Hunter• So, when you don’t include any access modifier,you are in fact giving your variable packageaccess.int x; // package access instance variable• Notice, it’s declared neither public norprivate.Superclasses and Subclasses
    • 48. Java I--Copyright © 2000 Tom Hunterprotected
    • 49. Java I--Copyright © 2000 Tom Hunter• protected allows the class itself, Subclassesand all classes in the same package to access themembers.• Generally speaking, protected offers greateraccess than package access.Superclasses and Subclasses
    • 50. Java I--Copyright © 2000 Tom Hunter• Use the protected access level when it’sappropriate for a class’s Subclasses to have accessto the member, but not for unrelated classes to haveaccess.• protected members are like family secrets—you don’t mind if someone in the family knows—but you don’t want outsiders to know.Superclasses and Subclasses
    • 51. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• The Access Modifier protected can be usedon either a method or an encapsulated datavariable.• protected serves as a middle groundbetween the private and public accessmodifier.
    • 52. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• A Superclass’s protected data variables may beaccessed only by:—methods of the Superclass—methods of the Subclass—methods of other classes in the same package.Or we can summarize:protected members have package access.
    • 53. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclassesprotected• protected access means the variable is:—public to the class,—private outside the class, and—public to the subclasses.• It’s like the Subclasses can reach up and getaccess to the data variables of the Superclass.
    • 54. Java I--Copyright © 2000 Tom HunterThesuperReference
    • 55. Java I--Copyright © 2000 Tom Hunter• Already, we know that the Superclass-Subclassinteraction has a big effect on the Constructor.• The Superclass Constructors are either implicitlyor explicitly called first in the Constructor of aSubclass.The super Referencesuper( whatever the Superclass needs)
    • 56. Java I--Copyright © 2000 Tom HunterThe super Referencesuper( whatever the Superclass needs)• Using this super reference, you can call thecall theConstructorConstructor of your Subclass’ Direct Superclass.• If you use this super reference, then itmust be the very first statement in theSubclass’ Constructor.
    • 57. Java I--Copyright © 2000 Tom Hunterpublic class Employee{String name;String SSN;public Employee( String nm, String soc ){name = nm;SSN = soc;}public double calc_pay(){return 0.0;}}
    • 58. Java I--Copyright © 2000 Tom Hunterpublic class HourlyEmployeeextends Employee{double hourly_rate;int hours;public HourlyEmployee(){// implicit (hidden) call to Superclass Constructor.hourly_rate = 0.0;hours = 0;}public HourlyEmployee( String n, String s, double r, int h ){// implicit (hidden) call to Superclass Constructor.hourly_rate = r;hours = h;}public double calc_pay(){return hours * hourly_rate;}}
    • 59. Java I--Copyright © 2000 Tom Hunterpublic class HourlyEmployeeextends Employee{double hourly_rate;int hours;public HourlyEmployee(){super( n, s ); // Explicit call to Superclass Constructorhourly_rate = 0.0;hours = 0;}public HourlyEmployee( String n, String s, double r, int h ){super( n, s );n // Explicit call to Superclass Constructorhourly_rate = r;hours = h;}public double calc_pay(){return hours * hourly_rate;}}
    • 60. Java I--Copyright © 2000 Tom Hunter• There is a similar statement that is used to callyour Subclass’ constructor within your Subclass.• Don’t get the two confused.The super Referencesuper( whatever the Superclass needs)this( whatever the Subclass needs)
    • 61. Java I--Copyright © 2000 Tom HunterSubclass can beTreatedas an Objectof theSuperclass
    • 62. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• A Subclass contains more than its Superclasscontains.• Because of that, we say inside of a Subclass is acomplete copy of its Superclass.
    • 63. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• On previous slides, we said a Subclass is anobject of the Superclass type.• Now, we take that one step further.
    • 64. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• A Subclass contains everything ( and more)required to make a complete example of theSuperclass...• Thus, we say an object of a Subclass can betreatedtreated as an object of its Superclass.• In other words, in certain situations, we canignore the difference between the Superclassand Subclass objects.
    • 65. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses“An object of a Subclass can be treatedas an object of its Superclass.”• What would stop this from being true?• Is there any part of the Superclass that ismissing from the Subclass?Nope—it’s all there.
    • 66. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses“An object of a Subclass can be treatedas an object of its Superclass.”• Certainly if we are asking a Subclass tofill in for its parentfill in for its parent, we throw away theextra stuff that the Subclass added, but—because a Subclass “is an” example of itsSuperclass—we can “treat the Subclass asan example of the Superclass.”
    • 67. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• And, if we only want to call the methodsfrom the Superclassand access the data variables that comefrom the Superclass—what’s the difference?
    • 68. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• Doing this might be interesting.• As long as we treat the reference like it only refersto the Superclass, we can handle a Subclass objectfrom a Superclass “reference.”• As long as we only call the methods thatexist in the Superclass, this will work fine.
    • 69. Java I--Copyright © 2000 Tom Hunterpublic class Employee{String name;String SSN;public double calc_pay(){return 0.0;}}public class HourlyEmployeeextends Employee{double hourly_rate;int hours;public double calc_pay(){return hours * hourly_rate;}}public class SalariedEmployeeextends Employee{double monthlySalary;public double calc_pay(){return monthlySalary;}}
    • 70. Java I--Copyright © 2000 Tom Hunterpublic class TestEmp{public static void main( String args[] ){double money = 0.0;HourlyEmployee hour;hour = new HourlyEmployee();money = hour.calc_pay();System.out.println( “Money=” + money );}}
    • 71. Java I--Copyright © 2000 Tom Hunterpublic class TestEmp{public static void main( String args[] ){double money = 0.0;SalariedEmployee salr;salr = new SalariedEmployee();money = salr.calc_pay();System.out.println( “Money=” + money );}}
    • 72. Java I--Copyright © 2000 Tom Hunterpublic class TestEmp{public static void main( String args[] ){double money = 0.0;Employee empl;empl = new SalariedEmployee();money = empl.calc_pay();System.out.println( “Money=” + money );}}• As long as we only call the methods thatexist in the Superclass, this will work fine.
    • 73. Java I--Copyright © 2000 Tom Hunterpublic class TestEmp{public static void main( String args[] ){double money = 0.0;Employee empl;empl = new SalariedEmployee();money = empl.calc_pay();System.out.println( “Money=” + money );}}• So, why in the world might we want to do this?
    • 74. Java I--Copyright © 2000 Tom Hunterpublic class RetiredEmployeeextends Employee{double monthlyPension;public double calc_pay(){return monthlyPension;}}• Imagine if—after we built our system—wedecided to add a class, for Retired Employees.• If we had built our program on a Superclassreference, then we wouldn’t have to rebuildanything.• The runtime environment sees what kind of objectwe have instantiated, and calls the right methodoverride !
    • 75. Java I--Copyright © 2000 Tom Hunterpublic class TestEmp{public static void main( String args[] ){double money = 0.0;Employee empl;empl = new RetiredEmployee();money = empl.calc_pay();System.out.println( “Money=” + money );}}• Caution, this works only when you’re calling amethod that exists in your Superclass, not one thatexists only in the Subclass.(And so now you see the advantage of identifyinga bunch of empty methods in your Superclass.)
    • 76. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• And (drumroll…) the whole process is called...
    • 77. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• More on Polymorphism• We can create a Superclass reference that is anarray.• Then, when we instantiate the array, we can attachall different kinds of Subclass objects to theSuperclass array reference.
    • 78. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• As long as we’re only calling methods that existin the Superclass, we can work our way through thearray and it will call all the correct overriddenversions of each individual Subclass object.
    • 79. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• The Superclass reference only knows about themethods that exist in the Superclass.• The Superclass only tries to call the methods itknows about.• That’s perfectly fine, because all the methods inthe Superclass are available in its Subclass.
    • 80. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• Therefore the Superclass isn’t aware that theobject it references can do a whole lot more thanthe Superclass thinks it can.
    • 81. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• So, “We can create a Superclass reference arraythat actually points to a Subclass object.”• As long as we treat those Subclass objects as ifthey were Superclass objects, (meaning we onlycall the methods in the Superclass) we have noproblems.
    • 82. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• The Subclass knows how to do everything itsparent Superclass can do.• The kids can do everything the parent can.
    • 83. Java I--Copyright © 2000 Tom Hunter• However, if we try to do it the other way around—treating the Superclass as if it were one of itschildren—then we can have...Superclasses and Subclassesproblemsproblems• Why? The Subclass can do many things theSuperclass cannot.• The kids can do many things the parent cannot.
    • 84. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• If we called the Superclass with the Subclass’sreference, then you might expect the Subclassreference can do all the things the kids can—andyou’d be wrong!
    • 85. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• If you want to go the other way, attach aSuperclass object to a Subclass reference,you have to do an explicit cast, as a wayof informing the compiler that you reallywant to do this dumb thing.
    • 86. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• “A Superclass object is notnot a Subclass object.”An HourlyEmployee is an Employee(Subclass is a Superclass object)but…An Employee is NOT an HourlyEmployee(Superclass is NOT a Subclass object)
    • 87. Java I--Copyright © 2000 Tom HunterSuperclasses and Subclasses• If you want to actually call some of themethods that don’t exist in the Superclass,then you have to first cast the object backto a reference of its own kind.
    • 88. Java I--Copyright © 2000 Tom HunterA Case Study ofInheriting a Class:The Rosetta Stone of Inheritance
    • 89. Java I--Copyright © 2000 Tom Hunter• Chapter 9, verse 9.4, page 391:• Point is the Superclass, although it (secretly)inherits off of Object, the ultimate Superclass.• It has two protected variables x and y thathold the location of the point.• Look at line 8, the “no argument Constructor.What is happening there?A Case Study of Inheriting a Class
    • 90. Java I--Copyright © 2000 Tom HunterPoint p;p = new Point();A Case Study of Inheriting a Class• You recognize what is above. “Point p” createsa reference “p ” to an object of type Point.• p = new Point(); fires the defaultConstructor for this class, thereby initializing theobject and making sure it starts in a stable state.
    • 91. Java I--Copyright © 2000 Tom HunterPoint p;p = new Point();A Case Study of Inheriting a Class• Line 11 calls another method of the class calledsetPoint( 0, 0 ).• Since this is the default or “no argument”constructor, the Constructor goes ahead and hardcodes the values “0, 0” that it sends to thesetPoint( 0, 0 )method.
    • 92. Java I--Copyright © 2000 Tom HunterA Case Study of Inheriting a Class• Look on line 10. See the comment there about the“implicit ( meaning unspoken) call to Superclassconstructor occurs here.”What does that mean?• Think about this carefully: we have always saidthat the Subclass contains the Superclass objectinside of it. Point is the (Subclass) to Object(Superclass).
    • 93. Java I--Copyright © 2000 Tom HunterA Case Study of Inheriting a Class• On line 10, right before we fire off the Subclass’sconstructor, we first fire the Superclass’sconstructor.• On line 15 is the argument-taking Constructor. Itagain fires the implicit constructor for the Superclass(Object) object.
    • 94. Java I--Copyright © 2000 Tom HunterA Case Study of Inheriting a Class• Circle inherits from Point. (extends Point)To create a circle you need a center point and aradius.• Since class Point already has the center pointinstance variables, we don’t need to create our owninstance variables—we inherit them from Point.• We do need to create our radius variable, however.
    • 95. Java I--Copyright © 2000 Tom HunterA Case Study of Inheriting a Class• Look at Line 48. This is the default no-argumentconstructor.• But, before we can initialize our Subclass, we haveto first initialize our Superclass, and so line 47shows where the implicit call to the (Point)Superclass happens.• And, of course, we know the first thing the Pointconstructor does is initialize Object, then Point.
    • 96. Java I--Copyright © 2000 Tom HunterA Case Study of Inheriting a Class• (page 392) Look at line 54,The Rosetta Stone of InheritanceThe Rosetta Stone of Inheritance:an explicit call to the Superclass constructor.• This is the argument-taking Constructor:before we can initialize the Circle, we have toinitialize Point, and before that, we have toinitialize Object.• On line 54, we see how we call the Superclassconstructor: super.
    • 97. Java I--Copyright © 2000 Tom HunterA Case Study of Inheriting a Class• When you use the explicit (meaning stated) callto a Superclass Constructor, it must be the veryfirst statement in the Constructor.
    • 98. Java I--Copyright © 2000 Tom HunterA Case Study of Inheriting a Class• Let’s pause and take down all the methods inour Superclass Point:Point()Point( a , b)setPoint( a, b)getX()getY()toString()• These are all the abilities of class Point.• So, a Point reference would be aware of thesemethods, and would be able to call them.
    • 99. Java I--Copyright © 2000 Tom HunterA Case Study of Inheriting a ClasstoString()• What these methods do is fairly clear, with theexception of the toString().• This method is inherited from Object.• We are supposed to override toString()in every one of our classes.• It turns the instance variables into a String andadds the name of the class. This is used fordebugging.
    • 100. Java I--Copyright © 2000 Tom HunterA Case Study of Inheriting a Class• Now go to page 392, lines 83-84: We aredeclaring some Point and Circle references.• On lines 87-88—as you would expect—we areinstanciating these objects by calling theirconstructors.• In line 90 we are calling the p.toString()reference, and the c.toString() reference.• Now, look at line 95. What is happening?
    • 101. Java I--Copyright © 2000 Tom HunterA Case Study of Inheriting a Class• On line 95, we are making it so that p (theSuperclass) is pointing to the same object as c.Point p = new Point();Circle c = new Circle();
    • 102. Java I--Copyright © 2000 Tom HunterPoint p;p = new Point();pCircle c;c = new Circle();c
    • 103. Java I--Copyright © 2000 Tom Hunterp = c;pcWhat if we try to call onlythe methods that both share?Will this “p” reference work correctly?This will work because any methodsone would expect to find in a Pointreference (p) already exist in the Circle object.
    • 104. Java I--Copyright © 2000 Tom Hunterc = p;pcNo ! A Circlereference wouldexpect manymethods that youwon’t find in aPoint object.Will this work for “c”?For this to even remotelywork, you would need to do a“downcast” ?
    • 105. Java I--Copyright © 2000 Tom HunterA Case Study of Inheriting a Class• On page 393, line 114, we’re attempting to dothis error by casting a Subclass reference to aSuperclass object.circleRef = (Circle) pointRef;• Notice how we use the operator:p instanceof Circle• This operator will tell us if p is a reference tothe class Circle.
    • 106. Java I--Copyright © 2000 Tom HunterA Case Study of Inheriting a Class• Attempting to have a Superclass reference pointto a Subclass object would lead to an error knownas a ClassCastException.
    • 107. Java I--Copyright © 2000 Tom HunterConstructorsandFinalizersinSubclasses
    • 108. Java I--Copyright © 2000 Tom HunterConstructors and Finalizers in Subclasses• Whenever you instantiate a Subclass object, theConstructors for the Superclass should be calledto initialize the instance variables of theSuperclass.• This instantiation can be done either implicitlyor explicitly (via the super reference).• These calls to instantiate the Superclass objectmust the first thing in your class’s Constructormethod.
    • 109. Java I--Copyright © 2000 Tom HunterConstructors and Finalizers in Subclasses• The opposite of the Constructor method is thefinalizer method.• If your class bothers to define a finalizermethod, then the implicit or explicit call to theSuperclass finalizer must be the last thing in thefinalizer method.
    • 110. Java I--Copyright © 2000 Tom HunterConstructors and Finalizers in Subclasses• You will always want to define your finalizermethod as protected, so that Subclasses thatinherit from your class can access its finalizer.• Classes that only use Superclass objects (notinherit them) cannot use the Superclass’s finalizermethods.
    • 111. Java I--Copyright © 2000 Tom HunterConstructors and Finalizers in Subclasses• Look at the output for Fig 9.5.Point ConstructorCircle ConstructorCircle FinalizerPoint Finalizer
    • 112. Java I--Copyright © 2000 Tom HunterConstructors and Finalizers in Subclasses• Turn to page 398. Lines 1-31 define class Point,which is our Superclass object.• On line 34, we define class Circle, a Subclass ofPoint.• On page 399, line 54 is class Circle’s finalizermethod. The last thing that Circle’s finalizermethod does is call its Superclass (Point)’sfinalizer method.super.finalizer();
    • 113. Java I--Copyright © 2000 Tom HunterConstructors and Finalizers in Subclasses• Warning! You must always use this “super”reference when you intend to call the finalizer ofthe Superclass.• If you omit the super, you’re actually callingthe finalizer of the method you’re already insideof--which is called infinite recursion.super.finalizer();
    • 114. Java I--Copyright © 2000 Tom HunterConstructors and Finalizers in Subclasses• You cannot do a cascading call to a Superclass.Instead, you have to rely on the Superclass itselfto call its own Superclasssuper.super.finalizer();

    ×