Inheritance and IS-A • Inheritance – inheriting ancestor’s traits – inheriting benefactor’s assets – inheriting instance members( methods/variables) • IS-A Relationship – human IS-A Mammal – salmon IS-A Fish – “Joe Doe” IS-A Student – A car made by this factory is an Acura. – ABMISpreadsheet IS-A BMISpreadsheet • IS-A vs. Inheritance – Human inherits Mammal traits, therefore Human IS-A Mammal – Inheritance => IS-A but not vice versa
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
• IS-A Relationship– human IS-A Mammal– salmon IS-A Fish– “Joe Doe” IS-A Student– A car made by this factory is an Acura.– ABMISpreadsheet IS-A BMISpreadsheet
• IS-A vs. Inheritance– Human inherits Mammal traits, therefore Human IS-A
Mammal– Inheritance => IS-A but not vice versa
Example
String History
public interface StringHistory {
}
public void addElement (String element);
public int size();
public String elementAt (int index);
Implementing the History
public class AStringHistory implements StringHistory { public final int MAX_SIZE = 50; String[] contents = new String[MAX_SIZE]; int size = 0; public int size() { return size;} public String elementAt (int index) { return contents[index]; } boolean isFull() { return size == MAX_SIZE; } public void addElement(String element) { if (isFull())
System.out.println("Adding item to a full history"); else {
contents[size] = element; size++;}
} }
Using the History
public static void main(String[] args) { StringHistory names = new AStringHistory(); while (true) { String input = readLine();
if (input.length > 0) if (input.charAt(0) == 'q') break; else if (input.charAt(0) == 'p' ) print(names);
else names.addElement(input);
}}
Printing a History
static void print(StringHistory strings) { System.out.println("******************"); for ( int elementNum = 0; elementNum < strings.size(); elementNum++)
public void deleteElement (String element) { shiftUp(indexOf(element));}
1
index
Multi-element window
4 James Dean
Joe Doe
Jane Smith
size array
John Smith
deleteElement(“Joe Doe”);
public void deleteElement (String element) { shiftUp(indexOf(element));}
Jane Smith
1
index
contents[index] = contents[index + 1];
deleteElement (String element)
4 James Dean
Joe Doe
Jane Smith
size array
John Smith
deleteElement(“Joe Doe”);
public void deleteElement (String element) { shiftUp(indexOf(element));}
Jane Smith
John Smith
3
void shiftUp (int startIndex) { for (int index = startIndex ; index + 1 < size; index++) contents[index] = contents[index + 1]; size--;}
2
index
indexOf (String element)
4 James Dean
Joe Doe
Jane Smith
size array
John Smith
indexOf(“Joe Doe”);
0
index
indexOf (String element)
4 James Dean
Joe Doe
Jane Smith
size array
John Smith
indexOf(“Joe Doe”);
1
index
public int indexOf (String element) { for ( index = 0; index < size && !element.equals(contents[index];
index++) ;
return index;}
public boolean member(String element)
4 James Dean
Joe Doe
Jane Smith
size array
John Smith
member(“Joe Doe”);
public int indexOf (String element) { for ( index = 0; index < size && !element.equals(contents[index];
index++) ;
return index;}
public boolean member (String element) { }
return indexOf (element) < size;
public void clear()
4 James Dean
Joe Doe
Jane Smith
size array
John Smith
clear()
public void clear() { while ( size > 0)
deleteElement(size -1);}
3210
public void clear()
4 James Dean
Joe Doe
Jane Smith
size array
John Smith
clear()
public void clear() { size = 0;}
0
addElement(“Mary Doe”)
0 Mary Doe
Joe Doe
Jane Smith
size array
John Smith
1
Logical but not Physical Extensions
clear( )
elementAt( )
size( )
member( )
deleteElement( )
addElement( )
StringDatabase
StringHistory
size( )
elementAt( )
addElement( )
IMPLEMENTS
IMPLEMENTS
elementAt( )
member( )
deleteElement( )
indexOf( )
size( )
addElement( )
shiftUp( )
size
contents
MAX_SIZE
AStringDatabase
clear( )
MAX_SIZE
size
contents
size( )
addElement( )
elementAt( )
AStringHistory
isFull( )
Physical and Logical Extensions
StringHistory
size( )
elementAt( )
addElement( )
EXTENDS
member( )
deleteElement( )String
Database
clear( )
member( )
deleteElement( )
indexOf( )
shiftUp( )
AStringDatabase
clear( )
IMPLEMENTS
IMPLEMENTS
EXTENDSSupertype
Subtype
MAX_SIZE
size
contents
size( )
addElement( )
elementAt( )
AStringHistory
isFull( )
SuperclassSubclass
Extending an Interface
public interface StringDatabase extends StringHistory {
}
public void member (String element);
public void deleteElement(String element);
public void clear();
public interface StringHistory {
}
public void addElement (String element);public int size();
public String elementAt (int index);
extends/ inherits
fromInherited members
Extending a Class
public class AStringDatabase extends AStringHistory implements StringDatabase { public void deleteElement (String element) { … } int indexOf (String element) { … } void shiftUp (int startIndex) { … } public boolean member(String element) { }
public void clear() { } }
Physical and Computer Inheritance
Human
AStringDatabase
PhysicalObject
Animal
Mammal
Primate
AStringHistory String
ObjectImplicit
extension
Regular Accord
Deluxe Accord
Car
Vehicle
StringDatabase
StringHistory
No Explicit Extension
public class AStringHistory implements StringHistory { public final int MAX_SIZE = 50; String[] contents = new String[MAX_SIZE]; int size = 0; public int size() { return size;} public String elementAt (int index) { return contents[index]; } boolean isFull() { return size == MAX_SIZE; } public void addElement(String element) { if (isFull())
System.out.println("Adding item to a full history"); else {
contents[size] = element; size++;}
} }
Equivalent Class Definition
public class AStringHistory extends Object implements StringHistory { public final int MAX_SIZE = 50; String[] contents = new String[MAX_SIZE]; int size = 0; public int size() { return size;} public String elementAt (int index) { return contents[index]; } boolean isFull() { return size == MAX_SIZE; } public void addElement(String element) { if (isFull())
System.out.println("Adding item to a full history"); else {
contents[size] = element; size++;}
} }
Some Methods of Class Object
MAX_SIZE
size
contents
size( )
addElement( )
elementAt( )
member( )
deleteElement( )
indexOf( )
shiftUp( )
AStringDatabase
AStringHistory
EXTENDS
clear( )
isFull( )
Object
EXTENDS
toString( )
equals( )
clone( )
(new AStringHistory()).toString()
(new AStringDatabase()).toString()
(new ACartesianPoint()).toString()
“hello”.toString()
‘h’.toString()
5.toString()
Used by println()
IS-A Relationships
Object
StringHistory AStringHistory String
AStringDatabaseStringDatabase
implements extends
Printing a History
static void print(StringHistory strings) { System.out.println("******************"); for ( int elementNum = 0; elementNum < strings.size(); elementNum++)
if (isFull()) System.out.println("Adding item to a full history");
else { contents[size] = element; size++;}
}
public void addElement(String element) { if (member(element)) return;
addElement(); }
Recursive call
More Overriding
MAX_SIZE
size
contents
size( )
addElement( )
elementAt( )
member( )
deleteElement( )
indexOf( )
shiftUp( )
AStringDatabase
AStringHistory
EXTENDS
clear( )
isFull( )
Object
EXTENDS
toString( )
equals( )
clone( )
AStringSet
addElement( )
Overriden Method
Overriding Method
toString( )
More Overriding
public String toString() {String retVal = “”;for (int i = 0; i < size; i++)
retVal += “:” + contents[i];return retVal;
}
stringSet.toString() “AStringSet@1eed58”
stringSet.toString() “:James Dean:John Smith”
Main classpublic static void main(String args[]) { StringDatabase names = new AStringDatabase(); while (true) { String input = Keyboard.readLine(); if (!(input.length() == 0))
if (input.charAt(0) == 'q') break;
else if (input.charAt(0) == 'p') print(names); else if (input.charAt(0) == 'd') names.deleteElement(input.substring(2, input.length())); else if (input.charAt(0) == 'm') System.out.println(names.member(input.substring(2, input.length()))); else if (input.charAt(0) == 'c') names.clear(); else names.addElement(input);
} }
Main with Switchpublic static void main(String args[]) { StringDatabase names = new AStringDatabase(); while (true) { String input = Keyboard.readLine(); if (!(input.length() == 0)) if (input.charAt(0) == 'q')
break; else switch (input.charAt(0)) {
case 'p': print(names); break; case 'd': names.deleteElement(input.substring(2, input.length())); break; case 'm': System.out.println(names.member(input.substring(2, input.length()))); break; case 'c': names.clear(); break; default: names.addElement(input);
} }
Breaks out of the loop
Breaks out of the switch
Switch expression
Switch arm
Switch case (value of switch
expressiuon)
Multi-case armspublic static void main(String args[]) { StringDatabase names = new AStringDatabase(); while (true) { String input = Keyboard.readLine(); if (!(input.length() == 0)) if (input.charAt(0) == 'q')
break; else switch (input.charAt(0)) {
case 'p’, ‘P’: print(names); break; case 'd’, ‘D’: names.deleteElement(input.substring(2, input.length())); break; case 'm’, ‘M’: System.out.println(names.member(input.substring(2, input.length()))); break; case 'c’, ‘C’: names.clear(); break; default: names.addElement(input);
} }
Omitting breakpublic static void main(String args[]) { StringDatabase names = new AStringDatabase(); while (true) { String input = Keyboard.readLine(); if (!(input.length() == 0)) if (input.charAt(0) == 'q')
break; else switch (input.charAt(0)) {
case 'p’, ‘P’: print(names); case 'd’, ‘D’: names.deleteElement(input.substring(2, input.length())); case 'm’, ‘M’: System.out.println(names.member(input.substring(2, input.length())));case 'c’, ‘C’: names.clear();default: names.addElement(input);
} }
Illegal Switch
switch (input ){case “print”: print(names); case “clear”: names.clear(); default: names.addElement(input);
}
Type of switch expression must be ordinal type
Ordinal Type
• Values of type are ordered.
• Each value has a unique successor and predecessor
intchar String double
Collections and Enumerations
• So far scanned enumeration fed into collection
• Could enumerate collections
Printing a History
static void print(StringHistory strings) { System.out.println("******************"); for ( int elementNum = 0; elementNum < strings.size(); elementNum++)
package collections;import enums.StringEnumeration;public class AStringHistory implements StringHistory {
public final int MAX_SIZE = 50;String[] contents = new String[MAX_SIZE];int size = 0;public StringEnumeration elements() {
return new AStringHistoryEnumerator(this);}public int size() {
return size;}…
}
Enumerator/Iterator Design Pattern
StringHistoryAStringHistoryEnumeration
CharHistoryACharHistoryEnumeration
NumberListANumberListEnumeration
CollectionCollection Enumeration
Design Pattern• Inspired by Architectural Pattern• Reusable programming pattern• Not specific class or interface, infinite family of
classes/interfaces• E.g.
– Enumeration
– Scanner pattern
• Language-independent pattern language• Usually involves multiple objects
– Collection and collection enumeration
Design Pattern
• Encyclopaedia of patterns
• Hard to read
• Not taught to undergrad students
• Large project offers opportunity!
Architectural Pattern
• Christopher 79– Each pattern is a three part rule, which
expresses a relation between a certain context, a problem, and a solution.
– Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of a solution to that problem, in such a way that you can use this solution a million times over
Screened-in porch
2nd story porch supported by 1st floor porch columns
Flat (not bay) window
DIFFERENT
No outside stairs to 2nd story
Wide plank siding
SIMILAR
Conventions for Variable-Sized Collection
public interface I {public void addElement (T t);public T elementAt (int index);
public int size();}
Arbitrary Type.
Read methods
Write method
Alternative Conventions for Variable-Sized Collection
public interface I {public void add (T t);public T get (int index);
public int size();}
Arbitrary Type.
Read methods
Write method
ObjectEditor understands both
Read vs. Write Methods
• Read Methods– Used to get components of object
– Getter methods
– size(), addElement()
• Write Methods– Used to change components of object
– Setter methods
– addElement(), deleteElement(), replaceElement()
• Distinction independent of conventions• Conventions used in Object Editor
Java Vectors and Enumerations
• Just like collections we defined
• Except they can store and enumerate arbitrary objects
nullVector Instance
Vectors (java.util.Vector)Vector v;
James Dean
Joe Doe
Point Instance
v = new Vector();v.addElement(“James Dean”)v.addElement(“Joe Doe”)
v.addElement(new ACartesianPoint(5, 5))
Vector Instance
v.addElement(new Vector())
v.addElement(5)
Object
Important Methods of Class Vector
public final int size() public final Object elementAt(int index) public final void addElement(Object obj) public final void setElementAt(Object obj, int index) public final void insertElementAt(Object obj, int index) public final boolean removeElement(Object obj) public final void removeElementAt(int index) public final int indexOf(Object obj) public final Enumeration elements()
Methods of Interface Enumeration (java.util.Enumeration)
public boolean hasMoreElements(); public Object nextElement();
Enumeration elements = vector.elements();while ( elements.hasMoreElements()) System.out.println(elements.nextElement();
Methods of Interface Enumeration (java.util.Enumeration)
public boolean hasMoreElements(); public Object nextElement();
for (Enumeration elements = vector.elements(); elements.hasMoreElements();) System.out.println(elements.nextElement();
Abstract methods vs. Interfaces• Public abstract methods subsumed by interfaces
– Useful only in languages such as C++ with no interfaces• Abstract class can be declared to implement interfaces:
public abstract class ACourse implements Course {…
} • Unimplemented methods become abstract methods to be
implemented by concrete subclasses. Do not need explicit implements clause in subclass if no additional public methods implemented,– public class ARegularCourse extends ACourse { …. }
• Separation of abstract and concrete methods with interfaces.
Abstract methods vs. Interfaces
• Non-public abstract methods relevant even in Java
• All interface methods must be public
• E.g. – abstract boolean isFull() ;
Useful abstract methodspublic abstract class ACollection {
public String getTitle() {return title;} public String getDepartment() {return dept};
abstract public String getNumber(); }
Should go in interface.
Uses default values
Default values.
Old ARegularCoursepublic class ARegularCourse extends ACourse
implements Course {int courseNum = 99;
public ARegularCourse (String theTitle, String theDept, int theCourseNum) {
super (theTitle, theDept);courseNum = theCourseNum;
} public int getNumber() {
return courseNum;}
}
No init
init in ARegularCoursepublic class ARegularCourse extends ACourse implements
Course {int courseNum = 99;
public ARegularCourse (String theTitle, String theDept, int theCourseNum) {
init (theTitle, theDept, theCourseNum);} public ARegularCourse() {}
public void init (String theTitle, String theDept, int theCourseNum) {
courseNum = theCourseNum;} public int getNumber() {
return courseNum;}
}
No super call
init in ARegularCoursepublic class ARegularCourse extends ACourse implements Course {
int courseNum = 99;
public ARegularCourse (String theTitle, String theDept, int theCourseNum) {
init (theTitle, theDept, theCourseNum);
}
public ARegularCourse() {
}
public void init (String theTitle, String theDept, int theCourseNum) {
super.init(theTitle, theDept);
courseNum = theCourseNum;
}
public int getNumber() {
return courseNum;
}
}
Two ways to construct
• Initialized construction– new ARegularCourse (“Intro. Prog”, “COMP”,
14);
• Construction and then initialization– (new ARegularCourse()).init(“Intro Prog.”,
“COMP”, 14)
Parameterized Constructors
• So far, one parameterized constructor in a class, that initializes all instance variables
• Can create multiple parameterized constructors– To initializes some subset of instance variables.– Use default values assigned by initializing declarations for the rest.
public ACourse (String theTitle) {title = theTitle;
}
• Add an init method for each parameterized constructor
Overloading, Polymorphism, and Dynamic dispatch
• Same method name works on different types.• Overloading
– Multiple (static or instance) methods with same name but different parameter types.
– Resolved at compile time based on parameter types
• Polymorphism– Same method implementation works on multiple object
types.
• Dynamic dispatch (or virtual methods)– Multiple instance methods with same name in different
classes
– Resolved at execution time based on type of target object