Download presentation
Presentation is loading. Please wait.
1
Introduction to Computer Science Inheritance Classes and Methods: Static Methods and Variables Unit 11
2
11- 2 Inheritance We've seen inheritance first in the robot world Inheritance allows a programmer to customize an existing class to a new application, by defining a new class that inherits from the first, but adds or redefines instance methods as necessary
3
11- 3 From the Robot World: Class Hierarchy (showing Attributes, not Methods) extends Containers filled material color Boxes length method 6 Cereal Boxes Cylinder extends length width height radius height type of cereal Software Boxes type of software extends Objects made from this class have all the attributes of the classes above them
4
11- 4 The Details, Defining a new Method, moveMile, inside a new class class MileWalker extends BasicRobot { void moveMile { move; move; move; move; move; move; move; move; } } New reserved words, class, extends, void
5
11- 5 Visually, What Have We Got? move turnLeft pickBeeper putBeeper turnOff BasicRobot x-location y-location direction num-beepers move turnLeft pickBeeper putBeeper turnOff moveMile MileWalker x-location y-location direction num-beepers extends
6
11- 6 So it is with Java Class C is a subclass of a class B: class C extends B { … } Objects of C contain all instance variables of B as well as those of C, respond to all the instance methods of B as well as of C, and C can redefine methods and override instance methods defined in B
7
11- 7 Example: Inheritance from class Time class Time { private int _hour, _minute; public Time (int h, int m) { _hour = h; _minute = m; } public void advanceMinutes (int m) { int totalMinutes = ((60*_hour) + _minute + m)% (24*60); if (totalMinutes < 0) totalMinutes = totalMinutes + (24*60); _hour = totalMinutes / 60; _minute = totalMinutes % 60; } public void printTime ( ) { … } // next page… }
8
public void printTime ( ) { if ((_hour == 0) && (_minute == 0)) System.out.print(“midnight”); else if ((_hour == 12) && (_minute == 0)) System.out.print(“noon”); else { if (_hour == 0) System.out.print(12); else if (_hour > 12) System.out.print(_hour - 12); elseSystem.out.print(_hour); if (_minute < 10) System.out.print(“:0”+ _minute); elseSystem.out.print(“:” + _minute); if (_hour < 12)System.out.print(“AM”); elseSystem.out.print(“PM”); } } } end of class Time
9
11- 9 Now We Want Customization So now we want to have a new class, to be used occasionally, called PreciseTime The class PreciseTime is mostly the same as Time, and we don't have to duplicate everything in Time, we'll just inherit from it However, PreciseTime will have a new instance variable, second, a new instance method, void advanceSeconds(int), and a new constructor
10
class PreciseTime extends Time { private int _second; public PreciseTime(int h, int m, int s) { super(h, m); _second = s; } public void advanceSeconds (int s) { int advMinutes = s / 60; _second += s % 60; if (_second < 0) { advMinutes--; _second += 60; } else if (_second >= 60) { advMinutes++; _second -= 60; } advanceMinutes(advMinutes); } }
11
11- 11 PreciseTime Objects of the class PreciseTime have instance variables _hour, _minute, and _second They respond to messages advanceMinutes, printTime, and advanceSeconds A PreciseTime object is also a Time object advanceSeconds causes a PreciseTime object to send itself an advanceMinutes message
12
11- 12 Example The program: public class Time1Mutate { public static void main (String[ ] args) { PreciseTime lunchtime = new PreciseTime(6, 10, 0); lunchtime.advanceSeconds(60); lunchtime.printTime( ); System.out.println( ); lunchtime.advanceSeconds(-61); lunchtime.printTime( ); System.out.println( ); } } Prints 6:11AM 6:09AM
13
11- 13 Inheritance Hierarchy Obviously, a class can have any number of subclasses, those subclasses can have subclasses, etc., creating an inheritance hierarchy Notice that printTime( ) remains unchanged so far, even when we call it from a PreciseTime object
14
11- 14 Everything's an Object… There's one special class, called Object, in the package java.lang All classes are considered descendants of Object. For example, Time actually extends Object: class Time { protected int _hour, _minute; … } We could write "class Time extends Object", but we don't have to
15
11- 15 The Time Has Come, The Time is Now We have seen numerous examples of Class methods Math.pow(x, y) was a method associated with the class Math, that computes x y Similarly with Math.abs( ), Math.sqrt( ), etc. And let’s not forget the main method in our client programs; it is a method in a class, but we never created an object from that class! public static void main (String[ ] args) {...
16
11- 16 Class Variables A Class Variable is a variable associated with the class, not with an object of the class There is only one instance of the class variable, not one instance per object To create a class variable, add the keyword “static” to the variable’s declaration
17
11- 17 Class Method A Class Method is a method associated with the class as a whole, not with an object You can’t invoke a class method f using o.f (where o is an object name), since there’s no object it’s connected to Instead, you write C.f (where C is the class name) Add “static” to the method definition Class methods have no access to instance variables (of objects) in the class
18
11- 18 Class and Objects _hour _minute Time addMinutes( int m ) void printTime( ) Time bill Attributes: _hour = 7 _minute = 18 Methods: Time addMinutes(int m) void printTime ( ) scott Attributes: _hour = 14 _minute = 41 Methods: Time addMinutes(int m) void printTime ( ) class objects
19
11- 19 Motivation A Class method and Class variables allow us to define things which exist, in a single “copy”, in the class, and which are accessible to the objects that were derived from the class
20
11- 20 Class and Objects with Class variables and Class Methods _hourstatic useMT _minute static void changeMT( ) Time addMinutes( int m ) void printTime( ) Time bill Attributes: _hour = 7 _minute = 18 Methods: Time addMinutes(int m) void printTime ( ) scott Attributes: _hour = 14 _minute = 41 Methods: Time addMinutes(int m) void printTime ( ) class objects
21
11- 21 Example Let’s say the Time class has been expanded, so that now in addition to printTime( ) there is another method called printMilitaryTime( ) (prints 13:30 instead of 1:30PM) We want a boolean variable called useMilitaryTime to be used to decide which of the two methods should be used to print all of the Time objects Where should this boolean variable exist?
22
11- 22 Possibility 1 Declare useMilitaryTime in the client program When printing object “now”, write: if (useMilitaryTime) now.printMilitaryTime( ); else now.printTime( );
23
11- 23 Problem with Possibility 1 Printing of Time objects may occur in many different places, from many different methods, not necessarily in the main( ) class The useMilitaryTime variable would need to be passed to all of them as an additional argument Clumsy
24
11- 24 Possibility 2 Make _useMilitaryTime an instance variable of Time, with an instance method that toggles it: public class Time { private boolean _useMilitaryTime = false; … public void toggleTimeFormat ( ) { _useMilitaryTime = !_useMilitaryTime; } public void printTime ( ) { if (_useMilitaryTime) … else … } }
25
11- 25 Problem with Possibility 2 now.toggleTimeFormat( ) changes the printing format for object “now” now.printTime( ) prints appropriately But the boolean variable is repeated in every Time object that we’ve created Since we want to control all Time printing, we would need to send the toggleTimeFormat( ) message to all Time objects that have been created Clumsy
26
11- 26 Where Should that Boolean Variable Sit? So putting the boolean variable in the client doesn’t work; too many different methods need access to it Putting it in the Time objects doesn’t work; we don’t really want multiple copies We need a variable that can be changed in a single place, and all objects have access to that shared variable
27
11- 27 The Class Variable Solution Objects scott and bill have access to a single copy of a variable called useMT, that sits in the class Time; it doesn’t belong to any specific object, but to the class
28
public class Time { private static boolean _useMilitaryTime = false; … public static void toggleTimeFormat ( ) { _useMilitaryTime = !_useMilitaryTime; } public void printTime ( ) { if (_useMilitaryTime) … else … } } Both toggleTimeFormat( ) (the class method) and printTime( ) (the instance method) refer directly to useMilitaryTime (with no need to write Time.useMilitaryTime)
29
11- 29 Use of the Class Method and Class Variable from Outside the Class If the client program writes: Time.toggleTimeFormat( ); then the single copy of useMilitaryTime in the class (referred to by all copies of printTime) is flipped The class variable could also be declared public, and referred to by Time.useMilitaryTime from outside the class
30
public class Time { private static boolean _useMilitaryTime = false; … public static void toggleTimeFormat ( ) { _useMilitaryTime = !_useMilitaryTime; } public void printTime ( ) { if (_useMilitaryTime) … else … } } Instance Methods Access Class Variables and Methods Class Methods Access Class Variables and Methods
31
11- 31 Instances Access Class, Class Accesses Class, but Class Doesn’t Access Instances A class method cannot access instance variables or invoke instance methods Think about it: the class method (like Time.toggleTimeFormat( ) ) is called without reference to any particular object. Logically, what object would it access?
32
11- 32 Container Classes, with no instance variables or methods There exist certain classes – container classes – whose whole purpose in life is to provide a convenient way of packaging a collection of methods They have no objects created from them; they have no constructors Math is an example of a class that simply provides a useful collection of methods: sin( ), sqrt( ), round( ), pow( ), abs( ), etc., and public static final doubles E and PI
33
11- 33 Overloading Methods We created multiple constructors for a Class, all with the same name but different numbers or types of arguments: class Time { private int _hour, _minute; public Time (int h, int m) { _hour = h; _minute = m; } public Time ( ) { _hour = 0; _minute = 0; ) public Time (int m) { _hour = m / 60; _minute = m % 60; } public Time addMinutes (int m) { … } public void printTime ( ) { … } }
34
11- 34 Example: Printing a formatted int or double We want to print a value, either an int or a double, in a field of given size w: 342 23.1 w = 7; number is right justified We could define methods to handle formatted printing of int and double, and give them different names, but that’s not necessary with overloading
35
11- 35 Overloading the printr Method The solution depends on two techniques First, to print a number, we can concatenate it with a string (which turns it into a string); this gives us a number right justified in a string of some length: String s = “ “ + i; For i = 3524, our string s would be 3524 number is right justified in the field of some length
36
11- 36 Grabbing the Right Side of the String Second, we can select a substring consisting of the trailing (rightmost) w characters using the string methods length( ) and substring( ) If i has been combined with blanks into a string s, then s.substring(s.length( ) - w) gives us i right-justified in a field of width w
37
class Format { private static String _blanks=“ “; private static String setw(int w, int i) { String s = _blanks + i; return s.substring(s.length( ) -w); } private static String setw(int w, double d) { String s = _blanks + d; return s.substring(s.length( ) -w); } public static void printr(int w, int i) { System.out.print(setw(w, i)); } public static void printr(int w, double d) { System.out.print(setw(w, d)); } private overloaded class methods public overloaded class methods private class variable
38
11- 38 What If the Overloading is Ambiguous? Format.printr(10, Math.PI) chooses the correct (second) version of printr( ) What about the following? static void f(int i, double x) { … } static void f(double x, int i) { … } … f(10, 20); Either version could be used You’ll get a compiler error
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.