Topics for Today • Protected members of classes • Super in constructors and other methods CSE 143 Java • Using “this” to run other constructors • Overloading, constructors and “this” • Overriding some common methods declared in Object – More About Inheritance equals, compareTo, clone • instanceof operator 10/9/2003 (c) 2001-3, University of Washington 04-1 10/9/2003 (c) 2001-3, University of Washington 04-2 Member Access in Subclasses Using Protected • public : accessible anywhere the class can be accessed • If we had declared the Employee instance variables protected, instead of private, then this constructor would be legal • private : accessible only inside the same class public HourlyEmployee(String name, int id, double pay) { • Does not include subclasses – derived classes have no special // initialize inherited fields permissions this.name = name; this.id = id; // initialize local fields • A new mode: protected this.payRate = pay; accessible inside the defining class and all its this.hoursWorked = 0.0; subclasses } • Use protected for "internal" things that subclasses also may need to access • But it's still poor code [why?] • Consider this carefully – often better to keep private data private and provide appropriate (protected) set/get methods 10/9/2003 (c) 2001-3, University of Washington 04-3 10/9/2003 (c) 2001-3, University of Washington 04-4 CSE143 Au03 04-1
Super Constructor Rules • Rule 1: If you do not write any constructor in a class, Java • If a subclass constructor wants to call a superclass constructor, assumes there is a zero-argument, empty one it can do that using the syntax ClassName( ) { } super(<possibly empty list of argument expressions>) • If you write any constructor, Java does not do this as the first thing in the subclass constructor's body • Rule 2: If you do not write super(…) as the first line of a • Example: constructor, the compiler will assume the constructor starts with public HourlyEmployee(String name, int id, double pay) { super( ); super(name, id); • Rule 3: When an extended class object is constructed, there must payRate = pay; be a constructor in the parent class whose parameter list matches hoursWorked = 0.0; the explicit or implicit call to super( … ) } • Corollary: a constructor is always called at each level of the • Good practice to always have a super(…) at the start of a inheritance chain when an object is created subclass's constructor 10/9/2003 (c) 2001-3, University of Washington 04-5 10/9/2003 (c) 2001-3, University of Washington 04-6 Super Overriding and Overloading (Review) • Another use for super: in any subclass, super.msg(args) • In spite of the similar names, these are very different can be used to call the version of the method in the • Overriding : replacing an inherited method in a subclass superclass, even if it has been overridden class One { • Can be done anywhere in the code – does not need to be at the public int method(String arg1, double arg2) { … } beginning of the calling method, as for constructors } • Often used to create “wrapper” methods class Two extends One { /** Return the pay of this manager. Managers receive a 20% bonus */ public int method(String arg1, double arg2) { … } public double getPay() { } double basePay = super.getPay(); • Argument lists and results must match exactly (number and return basePay * 1.2; types) } • Method called depends on actual (dynamic) type of the receiver • Question: what if we had written “this.getPay( )” instead? 10/9/2003 (c) 2001-3, University of Washington 04-7 10/9/2003 (c) 2001-3, University of Washington 04-8 CSE143 Au03 04-2
Overloading Overloaded Constructors and this • Overloading : a class may contain multiple definitions for • Classes often have several relatedConstructors constructors or methods with the same name, but • Common pattern: some provide explicit parameters while different argument lists others assume default values class Many { • “this” can be used at the beginning of a constructor to public Many( ) { … } execute another constructor in the same class public Many(int x) { … } public Many(double x, String s) { … } • Syntax similar to super public void another(Many m, String s) { … } • Can have other statements in the constructor following the public int another(String[ ] names) { … } “this” call • Parameter lists must differ in number and/or type of parameters • Good practice – can provide a single implementation of code Result types can differ, or not common to both constructors • Method calls are resolved automatically depending on number and (static) types of arguments – must be a unique best match 10/9/2003 (c) 2001-3, University of Washington 04-9 10/9/2003 (c) 2001-3, University of Washington 04-10 Example: HourlyEmployee Constructors Comparing Objects /** Construct an hourly employee with name, id, and pay rate */ • Object defines a boolean function equals to test whether public HourlyEmployee(String name, int id, double pay) { two objects are the same super(name, id); payRate = pay; • Object's implementation just compares objects for hoursWorked = 0.0; identity, using == } • This behavior is often not what you want // default pay for new hires • Probably more appropriate concept of equality: private static double defaultPay = 17.42; • obj1 .equals( obj2 ) should return true if obj1 and obj2 represent the same “value” /** Construct an hourly employee with name, id, and default pay rate */ • A class that wants this behavior must override equals( ) public HourlyEmployee(String name, int id) { this(name, id, defaultPay); Somewhat tricky to do right } 10/9/2003 (c) 2001-3, University of Washington 04-11 10/9/2003 (c) 2001-3, University of Washington 04-12 CSE143 Au03 04-3
instanceof Comparing The Order of Objects • The expression <object> instanceof <classOrInterface> is true if • Many objects have a natural linear or total order the object is an instance of the given class or interface (or any • For any two values, one is always <= the other subclass of the one given) • A boolean comparison doesn't tell about relative order • One common use: checking types of generic objects before casting • Type Object does not have a method for this kind of comparison /** Compare this Blob to another Blob and return true if equal, otherwise false */ (why not?) public boolean equals(Object otherObject) { • The most commonly used order comparison method has this kind if (otherObject instanceof Blob) { Blob bob = (Blob) otherObject; of signature: …. compare this to OtherObject and return appropriate answer … int compareTo(Object otherObject) } else { return false; • return negative, 0, or positive value in a conventional way } • The Comparable interface requires exactly this method to exist } • Overuse (or even use?) of instanceof is often a sign of bad design • Any class that provides compareTo should implement this interface that doesn’t use inheritance and overriding appropriately • A “marker” interface 10/9/2003 (c) 2001-3, University of Washington 04-13 10/9/2003 (c) 2001-3, University of Washington 04-14 Copying Object and clone( ) Main Ideas of Inheritance • Review: what does A = B mean? (Hint: draw the picture) • Main idea: use inheritance to relate similar classes • This behavior is not always desirable • Better modeling • In Java, the = operator cannot be overridden • Supports writing polymorphic code • Instead, a method to copy can be written • Avoids code duplication • obj .clone( ) should return a copy of obj with the “same” value • Other ideas: • Object's implementation just makes a new instance of the same class whose • Use protected rather than private for things that will be instance variables have the same values as obj needed by subclasses • Object's implementation is protected • Use overriding to make changes to superclass methods • If a subclass needs to do something different, e.g. clone some of the instance variables too, then it should override clone( ) • Use super in constructors and methods to invoke superclass • clone cannot be used at will... operations • Class must be marked as "Clonable" 10/9/2003 (c) 2001-3, University of Washington 04-15 10/9/2003 (c) 2001-3, University of Washington 04-16 CSE143 Au03 04-4
Recommend
More recommend