Outline 1 Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables: protected Inheritance and constructors, super The is-a vs. has-a relationship (Inheritance vs. Composition) Class hierarchies & the Object class Overriding vs. Overloading Polymorphism Factoring out Common Behavior Abstract methods and classes Interfaces: implements
Inheritance In real life, hierarchies of classes exist. 2 mycar is just as easily a member of the Ford class as the Automobile class Class Automobile Customer Class Ford CorporateCustomer object mycar radioshack
Inheritance: extends This relationship is supported in Java by inheritance. made possible by the extends keyword. 3 class Ford extends Automobile{......... Original class (Automobile) is the Base class. Newly defined class (Ford) is the Derived class. Base class must exist to make a Derived class.
Inheritance 4 Derived classes inherit all data from the Base class. Derived classes inherit all the method interfaces from the Base class, but may specify a new implementation. Derived classes may also add new methods. The Base class is referred to as super Base class = superclass; Derived class = subclass
Inheritance: BetterBR Example.1 5 BetterBR Want to create a BufferedReader from a file name without having to worry about code for the InputStreamReader, FileInputStream, and File classes. Want to be able to read an int as easily as we read a String. The user-defined BetterBR class extends the Java BufferedReader class BetterBR objects are also BufferedReader objects BetterBR objects can be used the same as BufferedReader objects
Inheritance : BetterBR Example.2 6 class BetterBR extends BufferedReader{ public BetterBR(String filename) throws IOException { super(new InputStreamReader( super invokes the base class constructor. new FileInputStream( new File(filename)))); public BetterBR() throws IOException { super(new InputStreamReader(System.in));............. If a derived class has additional data members then their initialization should take place after the invocation of the super constructor.
Inheritance : BetterBR Example.3............. 7 public int readint() throws Exception { string line; line = readline(); Why can we do this? return Integer.parseInt(line); readint() is a BetterBR method, but not a BufferedReader method.
Inheritance : BetterBR Example.4 8 main (String[] arg) throws Exception{ int i; String s; BetterBR bbr = new BetterBR( junk.txt ); i = bbr.readint(); while ( i >= 0) { System.out.println( i = + i); i = bbr.readint(); s = bbr.readline(); while ( s!= null ) { System.out.println( s = + s); s = bbr.readline(); 3 5 237-1 A line Line #2 Last line
Object States 9 A Derived class inherits, (takes on), the data members (instance variables) of the Base class. The data members define an object s state. A derived class may include (extend) additional data (and function) members.
Object States: ExtendedName Eg.1 10 class Name { private String firstname, lastname, title; public Name(String first, String last){ firstname = first; lastname = last; title = ; // ================================================ class ExtendedName extends Name{ private String middlename; How does ExtendedName s constructor ensure a valid state for Name? public ExtendedName(String firstname, String middlename, String lastname){? super(firstname, lastname); this.middlename = middlename; What does this do?
Object States : ExtendedName Eg.2 A two-parameter constructor: 11 public ExtendedName(String firstname, String lastname) { super(firstname, lastname); middlename = ;// this.middlename = ; How does this constructor ensure a valid state?
Object States : ExtendedName Eg.3 12 A derived class s methods should never put the base class in an invalid state. A valid state is: Meaningful in the base class Possible in the base class Invalid state public ExtendedName(String firstname, String middlename, String lastname){ super(, ); middlename = ; The above code would place the inherited base class instance variables in an invalid state because the base class constructors never specified empty string states.
Object States & Access 13 Inherited class may need to directly access the private instance variables in the base class! Private members of the base class may not be directly accessed by derived classes. How can you protect your original class from being corrupted by client code, but still allow derived class code to access/modify base class instance variables? Accessor and mutator methods could be provided, but they may be inappropriate for client code invocation. Some data members should be able to be changed by derived class code, but not by client class code? Solution: protected keyword
Object Access 14 Three ways to classify accessibility of class members: private, public, protected Protected members in the Base class are private in the Derived class Private members in the Base class are inaccessible in the Derived class, even to the methods of the Derived class. Public members in the Base class are public in the Derived class
Object states class Name { protected String firstname, lastname, title; 15 public Name(String first, String last){ firstname = first; lastname = last; // ================================================ class ExtendedName extends Name { private String middlename; public ExtendedName(String firstname, String middlename, String lastname){ super(firstname, lastname); title = ; //base member access this.middlename = middlename;
Object states 16 Which should you use in a base class? private, public, protected Some people think all base class data should be private Then the derived class can t possibly invalidate the base class! Others think all base class data should be protected Makes it easy to do what you want with the derived class Comparison: In base In derived public protected private Works like public Works like public Works like private Works like public Works like private inaccessible
Constructors 17 When a derived class s constructor is called: Room is reserved for all the data members of both the derived class and its base class in the same object. The base class data gets set up then the derived class data gets set up. Derived class constructor must pass needed info to the base class constructor: super(); firstname lastname title middlename
is-a vs. has-a 18 Is-a An object of a derived class is an object of the base class In the left picture, a is a Has-a This is how we ve programmed up until now. In the right picture, a has a
is-a vs. has-a 19 The is-a relationship is called inheritance The has-a relationship is called composition (aggregation) class Name2 { public Name2( String firstname, String middlename, String lastname ){... private Name n; private String middlename; What are some disadvantages to composition?
When to use Inheritance 20 If all methods of the original class X should be methods of the new class Y, then use inheritance. If some of the methods of the original class X should be methods of the new class Y, then use composition. If it feels right to say that a Y is an X (as in a part-timer is an employee ), then use inheritance. If it feels right to say that a Y has an X (as in an employee has a name ), then use composition.
Don t make this mistake: class Name { public String firstname, lastname; public Name (String f, String l){...; 21 /***********************************************/ class ExtendedName extends Name { public String firstname, lastname, middlename; public ExtendedName (String f, String m, String l){...; What s wrong here?
The Object class 22 We ve used the Object class many times. Vectors store only type object. An Object is the very first, basic class defined by Java. Every class implicitly inherits from the Object class (either directly or indirectly). It has some specific methods you can re-define (or override). Some are: boolean equals(object other) String tostring( )
Class hierarchies in Java Both of these are possible: Title could be moved from the base Name class since not all names have a title. Name 23 Name ExtendedName ExtendedName SuffixedName Two subclasses for 1 superclass SuffixedName Subclasses extended to another subclass
Overriding 24 When a method is defined in a base class, it may be overridden (redefined differently) in the derived class. Technique: 1) override a method in a derived class, (i.e. provide an implementation of a base class function in the derived class) 2) create an object of the derived type 3) invoke the overridden method Whether the object is cast as the base type or derived type, the derived method s implementation is used. Don t confuse this with overloading Overloading: writing 2 methods in one class with the same name, differing by parameter lists.
Overriding 25 class Name{ public String getinitials(){ return fname.substring(0,1) +. +... lname.substring(0,1) +. ; /***********************************************/ class ExtendedName extends Name{ public String getinitials(){ return fname.substring(0,1) +. + getmiddleinitial() +. +... lname.substring(0,1) +. ;
Definition: Polymorphism 26 Polymorphism, in programming, is the ability to write code that is independent of the exact type of objects upon which it is executing. Polymorphic code is general code that only relies upon the common properties of objects in an inheritance hierarchy. General polymorphic code treats all objects of an inheritance hierarchy as base class objects. Polymorphism depends on inheritance and overriding. An object of the subclass can be referred to as an object of the superclass. When an overridden method is invoked upon an object reference of the superclass, the body of the subclass s overridden method is executed, (not the base class implementation).
Polymorphism: simple example 27 Vector v; Name n = new Name( Bill, Clinton ); v.add(n); ExtendedName en = new ExtendedName( George, W, Bush ); v.add(en); /**********************************************/ At this point, we don t know (or care) what kind of Name is being referenced! for(int I=0; I < v.size(); I++){ String s = ( (Name) v.elementat(i) ).getinitials(); System.out.println(s); B.C. G.W.B.
Overriden Base Member Invocation 28 A derived class over-riding function may invoke the base class version by use of the super keyword class Name{ public void print(){ system.out.print( lastname +, + firstname);... /***********************************************/ class ExtendedName extends Name{ public void print(){ super.print(); //invoke base class version system.out.print(, + middlename);...
Do you understand? 29 Explain the difference between overloading and overriding Explain the difference between inheritance and polymorphism Explain the difference between base and derived What 3 things must we have in order for these concepts to be useful? Where is the Object class in the Java hierarchy? Why would you want to do any of this? Give examples.
Applets Applet classes inherit from the Applet class Powerful set of GUI tools / window management. 30 class mywebprogram extends Applet{ /******/
Factoring out Common Behavior 31 When designing a set of classes with some commonality, look for their common behavior Example: camera store sells: Lenses focal length, zoom capability (Boolean) Film storage temperature, # exposures Cameras w/lens(bool), shutter speed, body color... But all of them have: Description, quantity on hand, price, inventory number
Factoring out Common Behavior class InventoryItem{ InventoryItem( ){ // constructor String getdescription(){return desc; int getquantityonhand(){return qoh; int getprice(){return price; 32 String desc; // description int inventorynumber; int qoh; // quantity on hand int price;
Factoring out Common Behavior 33 class Lens extends InventoryItem{ Lens( ){ // constructor super( ); /* other code */ /* METHODS SPECIFIC TO LENS*/ boolean iszoom(){return zoom; double getfocallength(){return focallength; /* INSTANCE VARIABLES SPECIFIC TO LENS*/ boolean zoom; double focallength;
Abstract methods & classes 34 A base class doesn t have to define all its methods! It can simply provide a prototype. If any method in a class doesn t have an implementation, it is an abstract method. Any class with an abstract method is an abstract class. An abstract class cannot be instantiated. (You cannot create an object of that type.) Why are abstract classes useful then?
Abstract methods & classes 35 Suppose you want to print out your camera store inventory items. All items will be stored in the same vector, so when you getnextelement(), you won t know whether you have a lens, camera, or film. You could provide a method in InventoryItem called print(), and then override it in all subclasses But what would the body of InventoryItem.print() look like? You can t define it, because the info you print depends on the type of item.
Abstract methods & classes 36 abstract class InventoryItem{ public InventoryItem(){ // etc. abstract public void print(); // no body! // other stuff /**********************************/ class Lens extends InventoryItem{ void public print(){ if (zoom) System.out.printLn( Zoom ); System.out.println( Lens ); // other stuff
Abstract classes 37 Another example is the InputStream class. InputStream is abstract. You cannot instantiate it directly. But there are several derived classes which you can instantiate. StringBufferInputStream, FileInputStream, and FilterInputStream InputStreamReader s constructor requires an InputStream argument. We can give InputStreamReader an object from any derived class. Each derived class works differently, but InputStreamReader never needs to know what type of InputStream it has!
Interfaces 38 Sometimes you need to specify generic behavior for a group of classes that are not related in any obvious hierarchical way. Example: the Enumeration type. Suppose you add another inventory item to your camera store: a package deal, including a camera, several lenses, and several rolls of film. Your class must inherit from your InventoryItem class, for obvious reasons. But let s say you also want it to work as an Enumeration type spitting out one of the packaged items at a time.
Interfaces 39 Fortunately, Enumeration is not a class it s an interface. It has no method bodies, just prototypes. It is not a class. interface Enumeration{ Object nextelement(); boolean hasmoreelements();
The implements keyword class PackageDeal extends InventoryItem implements Enumeration{ 40 private Vector packageditems; public PackageDeal( ){ // etc... Object nextelement(){ boolean hasmoreelements(){
The implements keyword 41 Now, if you had a method that took an Enumeration and wrote out the contents myutils.writeenum(e, System.out); You could pass it your PackageDeal objects and it would do the same thing. myutils.writeenum(mypd, System.out);
The implements keyword 42 class myutils{ public static void writeenum(enumeration e, PrintStream output){ String s; while ( e.hasmoreelements() ){ s = e.nextelement().tostring(); output.println(s); tostring() inherited from Object class