Published on

  • Be the first to comment

  • Be the first to like this


  1. 1. <ul><li>Given: </li></ul><ul><li>public class Vehicle{ </li></ul><ul><li>private String make; //car info instance data </li></ul><ul><li>private String model; </li></ul><ul><li>private int year; </li></ul><ul><li>private double mpg; </li></ul><ul><li>public Vehicle(String mk, String mdl, int yr, double mileage){ </li></ul><ul><li>make = mk; </li></ul><ul><li>model = mdl; </li></ul><ul><li>year = yr; </li></ul><ul><li>mpg = mileage; </li></ul><ul><li>} </li></ul><ul><li>public void setMake(String nmake) { </li></ul><ul><li>make = nmake; </li></ul><ul><li>} </li></ul><ul><li>public void setModel(String nmodel) { </li></ul><ul><li>model = nmodel; </li></ul><ul><li>} </li></ul><ul><li>public void setYear(int nyear) { </li></ul><ul><li>year = nyear; </li></ul><ul><li>} </li></ul>
  2. 2. <ul><li>public String getMake() { </li></ul><ul><li>return make; </li></ul><ul><li>} </li></ul><ul><li>public String getModel() { </li></ul><ul><li>return model; </li></ul><ul><li>} </li></ul><ul><li>public int getYear() { </li></ul><ul><li>return year; </li></ul><ul><li>} </li></ul><ul><li>public double getMileage() { </li></ul><ul><li>return mpg; </li></ul><ul><li>} </li></ul><ul><li>public String toString() { </li></ul><ul><li>return year + &quot; &quot; + make + &quot; &quot; + model; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  3. 3. <ul><li>Inheritance : extend classes by adding methods and fields </li></ul><ul><li>This is one f orm of software reuse !! </li></ul><ul><li>Example: Car class </li></ul><ul><li>a Car is a Vehicle with trunksize </li></ul>class Car extends Vehicle { new methods new instance fields }
  4. 4. <ul><li>Car automatically inherits all methods and instance fields of Vehicle </li></ul><ul><li>Extended class = superclass ( Vehicle ), extending class = subclass ( Car ) </li></ul>Car mycar = new Car(“Ford”,”Mustang”, 1969); //assume Car constructor exists mycar.setMpg(10.5); // OK to use Vehicle method with Car object
  5. 5. An Inheritance Diagram <ul><li>Every class extends the Object class either directly or indirectly </li></ul>Figure 1: An Inheritance Diagram
  6. 6. <ul><li>In subclass, specify added instance fields and additional methods ; </li></ul>public class Car extends Vehicle{ // data private boolean convertible; private double trunksize; public void setConvert(boolean conv){ convertible = conv; } public boolean getConvert() { return convertible; } //calculate distance that can currently be traveled public double distance (double gallons) { return gallons * getMileage(); //use superclass method to access // private data inheritied from Vehicle }
  7. 7. <ul><li>In subclass, change (override) methods ; </li></ul>//class Car continued………….. //OVERRIDE the toString method public String toString() { return getYear() + &quot; &quot; + getModel() + &quot; trunk cap: &quot; + trunksize; } Note again, that call to inherited public method uses implicit object (no object need be specified) } //can USE superclass method public String toString() { return super.toString() + &quot;trunk cap:” + trunksize; }
  8. 8. Inheriting Instance Fields <ul><li>A subclass has no access to private fields of its superclass </li></ul><ul><li>Subclass must use public interface </li></ul><ul><li>Inherit field: All fields from the superclass are automatically inherited </li></ul><ul><li>Add field: Supply a new field that doesn't exist in the superclass </li></ul><ul><li>Can't override fields </li></ul><ul><li>What if you define a new field with the same name as a superclass field? </li></ul><ul><ul><li>Each object would have two instance fields of the same name </li></ul></ul><ul><ul><li>this.varname, super.varname </li></ul></ul><ul><ul><li>Fields can hold different values </li></ul></ul><ul><ul><li>Legal but extremely undesirable </li></ul></ul>
  9. 9. Inheriting Methods <ul><li>Override method: </li></ul><ul><ul><li>Supply a different implementation of a method that exists in the superclass </li></ul></ul><ul><ul><li>Must have same signature (same name and same parameter types) </li></ul></ul><ul><ul><li>If method is applied to an object of the subclass type, the overriding method is executed </li></ul></ul><ul><li>Inherit method: </li></ul><ul><ul><li>Don't supply a new implementation of a method that exists in superclass </li></ul></ul><ul><ul><li>Superclass method can be applied to the subclass objects </li></ul></ul><ul><li>Add method: </li></ul><ul><ul><li>Supply a new method that doesn't exist in the superclass </li></ul></ul><ul><ul><li>New method can be applied only to subclass objects </li></ul></ul>
  10. 10. Invoking a Super Class Method <ul><li>Can't just call </li></ul><ul><li>toString() in toString() method of Car </li></ul><ul><li>That is the same as this.toString() </li></ul><ul><li>Calls the same method (infinite recursion) </li></ul><ul><li>Instead, invoke superclass method super.toString() </li></ul>Continued…
  11. 11. Inheritance Hierarchies <ul><li>Sets of classes can form complex inheritance hierarchies </li></ul><ul><li>Example: </li></ul>Figure 3: A Part of the Hierarchy of Ancient Reptiles
  12. 12. Inheritance Hierarchies Example: Swing hierarchy Figure 4: A Part of the Hierarchy of Swing User Interface Components Continued…
  13. 13. Subclass Constructors <ul><li>super followed by a parenthesis indicates a call to a superclass constructor </li></ul><ul><li>public Car (String mk, String mdll, int yr, double miles,double trk){ </li></ul><ul><li>super(mk,mdl,yr,miles); </li></ul><ul><li>trunksize = trk; </li></ul><ul><li>} </li></ul><ul><li>Must be the first statement in subclass constructor </li></ul><ul><li>If subclass constructor doesn't explicitly call a super class constructor, default super is implicitly called </li></ul><ul><ul><li>Default constructor: constructor with no parameters </li></ul></ul><ul><ul><li>If all constructors of the superclass require parameters, then the compiler reports an error! </li></ul></ul>
  14. 14. Subclass Constructors <ul><li>Note: Vehicle does not have default constructor … </li></ul><ul><li>If we defined Car constructor as follows: </li></ul><ul><li>public Car (String mk, String mdll, int yr, double miles){ </li></ul><ul><li>setMake(mk); </li></ul><ul><li>setModel(mdl); </li></ul><ul><li>setYear(yr); </li></ul><ul><li>setMpg(miles); </li></ul><ul><li>} </li></ul><ul><li>This method will not compile, as implicit call to default Vehicle constructor is not possible!! </li></ul>
  15. 15. Converting Between Subclass and Superclass Types <ul><li>Ok to convert subclass reference to superclass reference </li></ul>Car myCar = new Car(“Chevy”, “Camaro”, 1973); Vehicle aCar = myCar; Object theCar = myCar; Note: all three reference variables are referring to the same object
  16. 16. <ul><li>Superclass references don't know the full story: </li></ul><ul><li>When you convert between a subclass object to its superclass type: </li></ul><ul><ul><li>The value of the reference stays the same–it is the memory location of the object </li></ul></ul><ul><ul><li>But, less information is known about the object </li></ul></ul>aCar.setMpg(7.8); // OK aCar.distance(67); //NO!! // No--not a method of the class to which aCar belongs
  17. 17. <ul><li>Why would anyone want to know less about an object? </li></ul><ul><li>To write reusable code when code only needs to know about superclass features… </li></ul><ul><li>FOR EXAMPLE ….. </li></ul><ul><li>what if we also had a Truck class </li></ul><ul><li>(next slide) </li></ul>
  18. 18. public class Truck extends Vehicle{ private boolean trailerHitch; private double bedLength; public void setTrailerHitch(boolean hitch){ trailerHitch = hitch; } public double getLen() { return bedLength; } //calculate Load that can be carried public double calcLoad (double lbPerCubicFoot) { return (bedLength * lbPerCubicFoot) / …etc ; } // toString etc………… } Suppose we have a Truck class too
  19. 19. Class Usage <ul><li>//can create and assign to same type reference </li></ul><ul><li>Vehicle v1 = new Vehicle(“ford”,“mustang”,1966, 28.5); </li></ul><ul><li>Car c1 = new Car(“vw”,”rabbit”, 1978, 35.2); </li></ul><ul><li>Truck t1 = new Truck(“MAC”,”pickup”, 1968, 16.0); </li></ul><ul><li>//a subclass is the superclass type, but not vice versa </li></ul><ul><li>Vehicle v2 = new Car(“cadillac”,”seville”, 1988, 16.0); </li></ul><ul><li>Vehicle v3 = new Truck(“MAC”,”pickup”, 1968, 16.0); </li></ul><ul><li>Car c2 = new Vehicle(“gmc”,”yukon”,122, 13.5); //error </li></ul><ul><li>//public superclass methods can be called by subclass object </li></ul><ul><li>v1.setMake(“Mercury”); </li></ul><ul><li>t1.setMake(“Toyota”); </li></ul><ul><li>c1.setMake(“Nissan”); </li></ul>
  20. 20. public class App{ public static void main(String[] args){ Vehicle newVehicle ; // one list to store all Vehicles ArrayList<Vehicle> inventory = new ArrayList<Vehicle>(); //while user wishes to enter vehicles while(JOptionPane.showInputDialog(&quot;Enter a vehicle?? Y/N&quot;).equals(&quot;Y&quot;)){ String whichone = JOptionPane.showInputDialog(&quot;(C)ar or (T)ruck&quot;); switch (whichone.charAt(0) ) { //determine which kind case 'C': newVehicle = new Car(); break; case 'T': newVehicle = new Truck(); break; default: newVehicle = new Car(); // car assumed as default type } // use same code to get details for cars & trucks newVehicle.setMake(JOptionPane.showInputDialog(&quot;make?&quot;)); newVehicle.setModel(JOptionPane.showInputDialog(“ model ?&quot;)); newVehicle.setYear(Integer.parseInt(JOptionPane.showInputDialog (&quot;year?&quot;))); inventory.add(newVehicle); } Application can work with Carsa and Trucks using same code
  21. 21. // what is our inventory String output = &quot;&quot;; for ( int i=0; i<inventory.size(); i++) output = output + &quot; &quot; + inventory.get(i); JOptionPane.showMessageDialog(null, output); } } Simple loop to outputs all Vehicle information -- The correct version of toString is selected at run time --- POLYMORPHISM!! Application can work with Cars and Trucks using same code
  22. 22. Converting Between Subclass and Superclass Types <ul><li>Occasionally you need to convert from a superclass reference to a subclass reference </li></ul><ul><li>This cast is dangerous: if you are wrong, an exception is thrown </li></ul>Vehicle myRide = new Car(“Chevy”, “Camaro”, 1973); myRide.setConv(true); // will cause compile error because // compiler doesn’t know it’s a Car Can only call setConv with a Car object Car thisCar = (Car) myRide; thisCar.setConv(true);
  23. 23. <ul><li>Solution: use the instanceof operator </li></ul><ul><li>instanceof : tests whether an object belongs to a particular type </li></ul>if (myRide instanceof Car) { Car thisCar = (Car) myRide; thisCar.setConv(true); }
  24. 24. Polymorphism <ul><li>Polymorphism: ability to refer to objects of multiple types with varying behavior </li></ul><ul><li>Polymorphism at work: </li></ul><ul><li>Depending on types of ride , different version of toString is called </li></ul>public void printIt(Vehicle ride){ System.out.println( ride.toString () );
  25. 25. Access Control <ul><li>Java has four levels of controlling access to fields, methods, and classes: </li></ul><ul><ul><li>public access </li></ul></ul><ul><ul><ul><li>Can be accessed by methods of all classes </li></ul></ul></ul><ul><ul><li>private access </li></ul></ul><ul><ul><ul><li>Can be accessed only by the methods of their own class </li></ul></ul></ul><ul><ul><li>package access </li></ul></ul><ul><ul><ul><li>The default, when no access modifier is given </li></ul></ul></ul><ul><ul><ul><li>Can be accessed by all classes in the same package </li></ul></ul></ul><ul><ul><ul><li>Good default for classes, but extremely unfortunate for fields </li></ul></ul></ul><ul><ul><li>protected access </li></ul></ul><ul><ul><ul><li>Can be accessed by subclasses and package </li></ul></ul></ul>
  26. 26. Recommended Access Levels <ul><li>Instance and static fields: Always private . Exceptions: </li></ul><ul><ul><li>public static final constants are useful and safe </li></ul></ul><ul><ul><li>Some objects, such as System.ou t, need to be accessible to all programs ( public ) </li></ul></ul><ul><ul><li>Occasionally, classes in a package must collaborate very closely (give some fields package access); inner classes are usually better </li></ul></ul>
  27. 27. Recommended Access Levels <ul><li>Methods: public or private </li></ul><ul><li>Classes and interfaces: public or package </li></ul><ul><ul><li>Better alternative to package access: inner classes </li></ul></ul><ul><ul><ul><li>In general, inner classes should not be public (some exceptions exist, e.g., Ellipse2D.Doubl e) </li></ul></ul></ul><ul><li>Beware of accidental package access (forgetting public or private ) </li></ul>
  28. 29. Object: The Cosmic Superclass <ul><li>All classes defined without an explicit extends clause automatically extend Object </li></ul>Figure 8: The Object Class is the Superclass of Every Java Class
  29. 30. Object: The Cosmic Superclass <ul><li>Most useful methods: </li></ul><ul><ul><li>String toString() </li></ul></ul><ul><ul><li>boolean equals(Object otherObject) </li></ul></ul><ul><ul><li>Object clone() </li></ul></ul>
  30. 31. The String toString() Method Object class provides a toString(), so all objects have one!! import java.awt.Rectangle; Rectangle rec1 = new Rectangle(5, 10, 20, 30); System.out.println(“rec1” + rec1); //outputs “ rec1 java.awt.Rectangle[x=5,y=10,width=20,height=30] &quot; String toString() is called whenever you concatenate a string with an object:
  31. 32. What if you don’t override the tostring Method ? <ul><li>Object class toString() method executed </li></ul><ul><li>Object class knows nothing about the specifics of your class </li></ul><ul><li>Object class toString consists of only two piece of info it has, class name and hash code (value based on storage address) </li></ul><ul><li>Try it: code a class Widget with no toString and write an application with: </li></ul><ul><li>1. Widget myWidget = new Widget(); </li></ul><ul><li>2. System.out.println(myWidget); </li></ul>
  32. 33. Overriding the tostring Method <ul><li>To provide a nicer representation of an object, override toString: </li></ul>public String toString() { return “Widget: Size: 5 &quot;; } Very simple to override toString, just provide a toString method which returns a String which is how you would want the object represented textually.
  33. 34. If (coin1 == coin2) <ul><li>== tests for equal location </li></ul>Two References to Same Objects
  34. 35. If (coin1.equals( coin2) ) <ul><li>Object class equals also tests for equal location </li></ul>Two References to Same Objects
  35. 36. Need to override the equals method so that equal contents are checked <ul><li>equals is intended to test for equal contents </li></ul>Two References to Equal Objects Continued…
  36. 37. Overriding the equals Method <ul><li>When redefining equals method, you cannot change object signature </li></ul><ul><li>public boolean equals ( Object obj) { </li></ul><ul><li>} </li></ul>Continued…
  37. 38. Overriding the equals Method <ul><li>Equals method should be based on instance data of two objects ….. </li></ul><ul><li>public boolean equals ( Object obj) { </li></ul><ul><li>if (make.equals(obj.make) &&model .equals(obj.model )&& </li></ul><ul><li>year == obj.year & mpg == obj.mpg) </li></ul><ul><li>return true; </li></ul><ul><li>else </li></ul><ul><li>return false; </li></ul><ul><li>} </li></ul>But… this will not compile because an Object object does not have make, model, year and mpg instance fields.
  38. 39. Overriding the equals Method <ul><li>need to CAST Object obj to a Vehicle object ….. </li></ul><ul><li>public boolean equals (Object obj) { </li></ul><ul><li>Vehicle vobj = (Vehicle) obj; </li></ul><ul><li>if (make.equals( v obj.make) && model.equals( v obj.model) && </li></ul><ul><li>year == v obj.year &&mpg == v obj.mpg) </li></ul><ul><li>return true; </li></ul><ul><li>else </li></ul><ul><li>return false; </li></ul><ul><li>} </li></ul>
  39. 40. Overriding the equals Method <ul><li>Need to be sure that obj IS an object before you cast to avoid ClassCastException . </li></ul><ul><li>public boolean equals (Object obj) { </li></ul><ul><li>if (obj instanceof Vehicle) { </li></ul><ul><li>Vehicle vobj = (Vehicle) obj; </li></ul><ul><li>if (make.equals(vobj.make) && model.equals(vobj.model)&& </li></ul><ul><li>year == vobj.year &&mpg == vobj.mpg) </li></ul><ul><li>return true; </li></ul><ul><li>else </li></ul><ul><li>return false; </li></ul><ul><li>} </li></ul><ul><li>else </li></ul><ul><li>return false; </li></ul><ul><li>} </li></ul>This will work fine for Vehicle objects, but We will need to use this method when checking Equality of our subclasses too … need to be more specific when checking for equal class types
  40. 41. Overriding the equals Method <ul><li>Need to be sure that obj IS an object before you cast to avoid ClassCastException . </li></ul><ul><li>public boolean equals (Object obj) { </li></ul><ul><li>if (getClass().equals(obj.getClass() )) { </li></ul><ul><li>Vehicle vobj = (Vehicle) obj; </li></ul><ul><li>if (make == vobj.make && model == vobj.model && </li></ul><ul><li>year == vobj.year &&mpg == vobj.mpg) </li></ul><ul><li>return true; </li></ul><ul><li>else </li></ul><ul><li>return false; </li></ul><ul><li>} </li></ul><ul><li>else </li></ul><ul><li>return false; </li></ul><ul><li>} </li></ul>getClass() is a method inherited from the Object class which returns a Class object
  41. 42. Overriding equals in the Car subclass <ul><li>public boolean equals (Object obj) { </li></ul><ul><li>if ( super.equals(obj) == false) </li></ul><ul><li>return false; </li></ul><ul><li>else { // we now know they are both Cars, and </li></ul><ul><li>// super class fields are equal </li></ul><ul><li>// need to check additional Car field </li></ul><ul><li>Car tobj = (Car) obj; </li></ul><ul><li>return ( convertible == tobj.convertible && </li></ul><ul><li>trunksize == tobj.trunksize); </li></ul><ul><li>} </li></ul>
  42. 43. Object assignment ……. <ul><li>Copying an object reference gives two references to same object </li></ul>Vehicle myCar = new Car(); Vehicle car = myCar;
  43. 44. Object class has a Object clone() Method <ul><li>Object class clone() method returns a copy of the invoking object </li></ul><ul><li>Using the clone() method is inherited from the object class by all subclasses, BUT ACCESS is PROTECTED, so method not accessible by application class. </li></ul>Vehicle myVec = new Vehicle(“Toyota” , “Corolla”, 1967, 34.5); //Vehicle inherits // clone method from Object class Vehicle anotherVec = (Vehicle) myVec.clone(); //BUT application can not call it!! This is a security measure added to the Java language with Java 1.2. At that point the Java language’s popularity as a Web programming language was becoming apparent.
  44. 45. An object can ONLY be cloned IF it’s class overrides the Object clone() method <ul><li>public class Vehicle { </li></ul><ul><li>public Object clone() { //same signature for override </li></ul><ul><li>return super.clone(); // calls superclass Object’s clone </li></ul><ul><li>} </li></ul>Vehicle myVec = new Vehicle(“Toyota” , “Corolla”, 1967, 34.5); Vehicle anotherVec =(Vehicle) myVec.clone(); BUT …. Java has one more security measure for cloning.
  45. 46. An object can ONLY be cloned IF it’s class overrides the Object clone() method <ul><li>//class which overrides Clone MUST implementCloneable </li></ul><ul><li>public class Vehicle implements Cloneable { </li></ul><ul><li>{ </li></ul><ul><li>public Object clone() { </li></ul><ul><li>try{ </li></ul><ul><li>return super.clone(); //Object’s clone throws checked exception if </li></ul><ul><li>//cloneable not implemented, so must </li></ul><ul><li>// be called within a try/catch block </li></ul><ul><li> } </li></ul><ul><li> catch(Exception e) { </li></ul><ul><li> return null; </li></ul><ul><li> } </li></ul><ul><li>} </li></ul>
  46. 47. The Object.clone Method <ul><li>Creates shallow copies </li></ul>Figure 12: The Object.clone Method Makes a Shallow Copy