given: public class vehicle{ private string make; //car info instance data
DESCRIPTION
Given: public class Vehicle{ private String make; //car info instance data private String model; private int year; private double mpg; public Vehicle(String mk, String mdl, int yr, double mileage){ make = mk; - PowerPoint PPT PresentationTRANSCRIPT
Given:public class Vehicle{ private String make; //car info instance data private String model; private int year; private double mpg; public Vehicle(String mk, String mdl, int yr, double mileage){ make = mk; model = mdl; year = yr; mpg = mileage; } public void setMake(String nmake) { make = nmake; }
public void setModel(String nmodel) { model = nmodel; }
public void setYear(int nyear) { year = nyear; }
public String getMake() { return make; }
public String getModel() { return model; }
public int getYear() { return year; }
public double getMileage() { return mpg; }
public String toString() { return year + " " + make + " " + model; }}
• Inheritance: extend classes by adding methods and fields
This is one form of software reuse !!• Example: Car class a Car is a Vehicle with trunksize
class Car extends Vehicle{ new methods new instance fields }
• Car automatically inherits all methods and instance fields of Vehicle
• Extended class = superclass (Vehicle), extending class = subclass (Car)
Car mycar = new Car(“Ford”,”Mustang”, 1969); //assume Car constructor exists
mycar.setMpg(10.5); // OK to use Vehicle method with Car object
An Inheritance Diagram
• Every class extends the Object class either directly or indirectly
Figure 1:An Inheritance Diagram
• In subclass, specify added instance fields and additional methods ;
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 }
• In subclass, change (override) methods ;
//class Car continued…………..
//OVERRIDE the toString method public String toString() { return getYear() + " " + getModel() + " trunk cap: " + 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() + "trunk cap:” + trunksize; }
Inheriting Instance Fields• A subclass has no access to private fields of its
superclass • Subclass must use public interface • Inherit field: All fields from the superclass are automatically
inherited • Add field: Supply a new field that doesn't exist in the
superclass • Can't override fields
• What if you define a new field with the same name as a superclass field? Each object would have two instance fields of the same name this.varname, super.varname Fields can hold different values Legal but extremely undesirable
Inheriting Methods• Override method:
Supply a different implementation of a method that exists in the superclass
Must have same signature (same name and same parameter types)
If method is applied to an object of the subclass type, the overriding method is executed
• Inherit method: Don't supply a new implementation of a method that exists in
superclass Superclass method can be applied to the subclass objects
• Add method: Supply a new method that doesn't exist in the superclass New method can be applied only to subclass objects
Invoking a Super Class Method
• Can't just call
toString() in toString() method of Car
• That is the same asthis.toString()
• Calls the same method (infinite recursion)
• Instead, invoke superclass methodsuper.toString()
Continued…
Inheritance Hierarchies• Sets of classes can form complex inheritance hierarchies • Example:
Figure 3:A Part of the Hierarchy of Ancient Reptiles
Inheritance Hierarchies Example:Swing hierarchy
Figure 4:A Part of the Hierarchy of Swing User Interface Components
Continued…
Subclass Constructors• super followed by a parenthesis indicates a
call to a superclass constructor public Car (String mk, String mdll, int yr, double miles,double trk){
super(mk,mdl,yr,miles);
trunksize = trk;
}
• Must be the first statement in subclass constructor
• If subclass constructor doesn't explicitly call a super class constructor, default super is implicitly called Default constructor: constructor with no parameters If all constructors of the superclass require parameters, then the compiler reports an error!
Subclass Constructors• Note: Vehicle does not have default constructor …
• If we defined Car constructor as follows:
public Car (String mk, String mdll, int yr, double miles){ setMake(mk); setModel(mdl); setYear(yr); setMpg(miles);}
This method will not compile, as implicit call to default Vehicle constructor is not possible!!
Converting Between Subclass and Superclass Types
• Ok to convert subclass reference to superclass reference
Car myCar = new Car(“Chevy”, “Camaro”, 1973); Vehicle aCar = myCar; Object theCar = myCar;
Note: all three reference variables are referring to the same object
• Superclass references don't know the full story:
• When you convert between a subclass object to its superclass type: The value of the reference stays the same–it is the
memory location of the object But, less information is known about the object
aCar.setMpg(7.8); // OK aCar.distance(67); //NO!! // No--not a method of the class to which aCar belongs
• Why would anyone want to know less about an object?
• To write reusable code when code only needs to know about superclass features…
• FOR EXAMPLE …..
what if we also had a Truck class
(next slide)
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
Class Usage//can create and assign to same type referenceVehicle v1 = new Vehicle(“ford”,“mustang”,1966, 28.5);Car c1 = new Car(“vw”,”rabbit”, 1978, 35.2);Truck t1 = new Truck(“MAC”,”pickup”, 1968, 16.0);
//a subclass is the superclass type, but not vice versaVehicle v2 = new Car(“cadillac”,”seville”, 1988, 16.0);Vehicle v3 = new Truck(“MAC”,”pickup”, 1968, 16.0);Car c2 = new Vehicle(“gmc”,”yukon”,122, 13.5); //error
//public superclass methods can be called by subclass object v1.setMake(“Mercury”); t1.setMake(“Toyota”); c1.setMake(“Nissan”);
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("Enter a vehicle?? Y/N").equals("Y")){ String whichone = JOptionPane.showInputDialog("(C)ar or (T)ruck"); 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("make?")); newVehicle.setModel(JOptionPane.showInputDialog(“ model ?")); newVehicle.setYear(Integer.parseInt(JOptionPane.showInputDialog ("year?"))); inventory.add(newVehicle); }
Application can work with Carsa and Trucks using same code
// what is our inventory String output = ""; for ( int i=0; i<inventory.size(); i++) output = output + "\n" + 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
Converting Between Subclass and Superclass Types• Occasionally you need to convert from a superclass reference
to a subclass reference
• This cast is dangerous: if you are wrong, an exception is thrown
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);
• Solution: use the instanceof operator • instanceof: tests whether an object
belongs to a particular type
if (myRide instanceof Car) { Car thisCar = (Car) myRide; thisCar.setConv(true); }
Polymorphism
• Polymorphism: ability to refer to objects of multiple types with varying behavior
• Polymorphism at work:
• Depending on types of ride, different version of toString is called
public void printIt(Vehicle ride){
System.out.println( ride.toString() );
Access Control
• Java has four levels of controlling access to fields, methods, and classes: public access
• Can be accessed by methods of all classes private access
• Can be accessed only by the methods of their own class package access
• The default, when no access modifier is given • Can be accessed by all classes in the same package • Good default for classes, but extremely unfortunate for fields
protected access • Can be accessed by subclasses and package
Recommended Access Levels
• Instance and static fields: Always private. Exceptions: public static final constants are useful and safe
Some objects, such as System.out, need to be accessible to all programs (public)
Occasionally, classes in a package must collaborate very closely (give some fields package access); inner classes are usually better
Recommended Access Levels
• Methods: public or private
• Classes and interfaces: public or package Better alternative to package access: inner classes
• In general, inner classes should not be public (some exceptions exist, e.g., Ellipse2D.Double)
• Beware of accidental package access (forgetting public or private)
Object: The Cosmic Superclass
• All classes defined without an explicit extends clause automatically extend Object
Figure 8:The Object Class is the Superclass of Every Java Class
Object: The Cosmic Superclass• Most useful methods:
String toString()
boolean equals(Object otherObject)
Object clone()
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]"
String toString() is called whenever you concatenate a string with an object:
What if you don’t override the tostring Method ?
• Object class toString() method executed• Object class knows nothing about the specifics of
your class• Object class toString consists of only two piece of
info it has, class name and hash code (value based on storage address)
• Try it: code a class Widget with no toString and write an application with:
• 1. Widget myWidget = new Widget();• 2. System.out.println(myWidget);
Overriding the tostring Method
• To provide a nicer representation of an object, override toString:
public String toString() { return “Widget: Size: 5 "; }
Very simple to override toString, just provide a toString method which returns a String which is how you would want the object represented textually.
If (coin1 == coin2)
• == tests for equal location
Two References to Same Objects
If (coin1.equals( coin2) )
• Object class equals also tests for equal location
Two References to Same Objects
Need to override the equals method so that equal contents are checked
• equals is intended to test for equal contents
Two References to Equal Objects
Continued…
Overriding the equals Method
When redefining equals method, you cannot change object signature
public boolean equals (Object obj) {
}
Continued…
Overriding the equals Method
Equals method should be based on instance data of two objects …..
public boolean equals (Object obj) { if (make.equals(obj.make) &&model .equals(obj.model )&& year == obj.year & mpg == obj.mpg) return true; else return false;
}
But… this will not compile becausean Object object does not have make,model, year and mpg instance fields.
Overriding the equals Method
need to CAST Object obj to a Vehicle object ….. public boolean equals (Object obj) { Vehicle vobj = (Vehicle) obj; if (make.equals( vobj.make) && model.equals(vobj.model) && year == vobj.year &&mpg == vobj.mpg) return true; else return false;
}
Overriding the equals MethodNeed to be sure that obj IS an object before you cast to avoid ClassCastException . public boolean equals (Object obj) { if (obj instanceof Vehicle) { Vehicle vobj = (Vehicle) obj; if (make.equals(vobj.make) && model.equals(vobj.model)&& year == vobj.year &&mpg == vobj.mpg) return true; else return false; } else return false;
}
This will work fine for Vehicle objects, butWe will need to use this method when checkingEquality of our subclasses too … need to be more specific when checking for equal class types
Overriding the equals MethodNeed to be sure that obj IS an object before you cast to avoid ClassCastException . public boolean equals (Object obj) { if (getClass().equals(obj.getClass() )) { Vehicle vobj = (Vehicle) obj; if (make == vobj.make && model == vobj.model && year == vobj.year &&mpg == vobj.mpg) return true; else return false; } else return false;
}
getClass() is a method inherited from theObject class which returns a Class object
Overriding equals in the Car subclass
public boolean equals (Object obj) {
if (super.equals(obj) == false) return false;
else { // we now know they are both Cars, and // super class fields are equal // need to check additional Car field Car tobj = (Car) obj; return ( convertible == tobj.convertible && trunksize == tobj.trunksize);
}
Object assignment …….
• Copying an object reference gives two references to same object
Vehicle myCar = new Car();Vehicle car = myCar;
Object class has a Object clone() Method • Object class clone() method returns a copy of the invoking object • Using the clone() method is inherited from the object class by all
subclasses, BUT ACCESS is PROTECTED, so method not accessible by application class.
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. Atthat point the Java language’s popularity as a Web programming languagewas becoming apparent.
An object can ONLY be cloned IF it’s class overrides the Object clone() method
public class Vehicle {
public Object clone() { //same signature for override
return super.clone(); // calls superclass Object’s clone
}
Vehicle myVec = new Vehicle(“Toyota” , “Corolla”, 1967, 34.5); Vehicle anotherVec =(Vehicle) myVec.clone();
BUT …. Java has one more security measure for cloning.
An object can ONLY be cloned IF it’s class overrides the Object clone() method
//class which overrides Clone MUST implementCloneable
public class Vehicle implements Cloneable { {public Object clone() { try{ return super.clone(); //Object’s clone throws checked exception if //cloneable not implemented, so must // be called within a try/catch block } catch(Exception e) { return null; } }
The Object.clone Method
• Creates shallow copies
Figure 12:The Object.clone Method Makes a Shallow Copy