240 likes | 348 Views
Big Ideas behind Inheritance. Can you think of some possible examples of inheritance hierarchies?. Big Idea #1: Creating hierarchies by extending classes. Sub classes extend super classes IS A relationship (arrow)
E N D
Can you think of some possible examples of inheritance hierarchies?
Big Idea #1: Creating hierarchies by extending classes • Sub classes extend super classes • IS A relationship (arrow) • Constructors that use good style will always call the super constructor. The call to super() must be the first action in constructors. • All fields and methods are inherited by sub classes • Private fields in super class CANNOT be accessed in a sub class. • Methods need only be overridden when a change to object behavior (methods) is needed in the sub class. • Super is only used with methods when a method has been overridden. i.e. to distinguish between super.speak() and speak() • super.super.someMethod() is not allowed in Java. (for more see chart in Barron’s AP Book on page 191)
The Cosmic superclass • The Object class is know as the cosmic superclass because all other java classes extend it by default (implied). • It has some standard methods such as toString(), and equals(Object other) which all other classes inherit and often override. • This is where the “invisible” default constructor that all classes inherit or override comes from.
Big Idea #2: Polymorphism Polymorphism the process of choosing which class’ methods will be execute at run time. When polymorphic code is written it is not known which method will be called at compiletime; the decision is made at run time. This is also called “dynamic binding,” “late binding,” or “run time binding.” i.e. Consider this polymorphic method – public void impound(Pet p) { //implementation not shown }
Right under your nose • System.out.println() has used Inheritance all along How so? Let’s try it.
Big Idea #3: Abstract Classes and Interfaces • Inheritance can be used to REQUIRE OR SPECIFCY WHAT methods MUST be overridden. • An abstract method MUST be overridden. • An interface is a totally abstract class. • Interfaces are essential to uniformity in OOP and when leveraged correctly they are powerful timesavers.
Abstract methods • You make a method abstract when you want to force it to have to be overridden by sub classes. • Once a class has at least one abstract method then the whole class is considered abstract. • Abstract classes are designed to be extended and even though they do contain constructors, they can never be instantiated themselves. • Abstract classes can contain both abstract and non abstract methods. The best way to understand all this is by working with an example yourself….the Pet class
What is an Interface? • If every method were to be abstract in a class, then you may as well just create an interface. • Interfaces seem trivial at first glance but they are in fact EXTREMELY useful • Interfaces are usually named for adjectives (i.e. Comparable, Talkative, etc.) • A class implements an interface when it contains all methods required by the interface. • An interface can be thought of as a set of “requirements” that a class must have if it chooses to implement the interface. This enforces uniformity and promotes polymorphism.
Interfaces • An interface never contains any implementations (no methods, no instance fields) • Interfaces can declare constants. • You can NEVER instantiate an interface! • i.e. new Comparable() make NO sense • A class may implement MORE than one interface • A class may EXTEND another class and IMPLEMENT interfaces • i.e. Dog extends Pet implements Trainable (extends comes first)
Task: Trying out an Interface Let’s make it so we can tell objects of two UNRELATED class both to do the same action the same way. i.e make Pets and Persons both speak() 1) Add the simplistic Person class to the same project as Pet. 2 Create a new Interface called Talkative which returns a method speak that takes no parameters and which returns a String . 3) Make Pet implement Talkative: Change the makeSound method to be named speak in Pet and all your sub pet classes. 4) Make Person implement Talkative too. • Create an Person object with a Person reference variable person1. Tell it to speak. • Create an Pet object with a Pet reference variable pet1. Tell it to speak. • Replace your Person reference variable with a Talkative reference variable t1. Tell t1 to speak() • Replace your Pet reference variable with a Talkative reference variable t2. Tell t2 to speak() • Finally create an array of 3 Talkative objects and fill it with 2 persons and a pet. Loop through and tell them all to speak().QUESTION – Can you ever say new Talkative() ? What about new Talkative[] ?
Examples of Interfaces From GridWorld Grid<E> interface requires these methods in any Grid class intgetNumRows() intgetNumCols() booleanisValid(Location loc) E put(Location loc, E obj) E remove(Location loc) E get(Location loc) ArrayList<Location> getOccupiedLocations()ArrayList<Location> getValidAdjacentLocations(Location loc)ArrayList<Location> getEmptyAdjacentLocations(Location loc)ArrayList<Location> getOccupiedAdjacentLocations(Location loc)ArrayList<E> getNeighbors(Location loc) Implemented by AbstractGridwhich is extended by BoundedGrid and UnboundedGridSO FAR……
Examples of Interfaces Most famous interface is the Comparable interface http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html Comparable “imposes a total ordering on the objects of each class that implements it” public Interface Comparable<T> { intcompareTo(T o) } You have used compareTo with Strings i.ew. s1.compareTo(s2)
Aside- What is <T> or <E> ? • “of type” parameter • Consider it part of the interface or class or variable name. Examples – ArrayList<Location> Grid<E> ArrayList<Actor>
Comparable • Not all classes can implement Comparable • Works for classes with a “Natural Order” • Works for BankAccount, String • How about a class called Point? • Location class?
Why bother to make things Comparable? • Because now you can sortthem and it is really easy!!! • Create an array of your objects • Import java.util.Arrays(static class) • Then: Arrays.sort(yourarray); Let’s make the Person class Comparable together.
Task: the power of the Comparable interface • Bring the BankAccount class into your Pet project. Make BankAccount and Pet comparable. Add a field if you wish. • Test them using BlueJ. • Create a test class called ComparableTestsIn the main method create an array of 3 Pets and an array of 3 BankAccounts. • Test by looping through the pets and print each pet’s name and make it speak. (look at Zoo for help) • Test by looping through the BankAccounts and printSlip on each. (look at Bank for help) • Now sort the arrays! Loop through each and print again. • Final replace the two Arrays with ONE array of Comparable objects and test.
Casting Example • Assume: Dog extends Pet • Assume Pet has methods getName and speak. • Assume Dog inherits getName from Pet, overrides speak, and has another method beg. Dog fido = new Dog(); Pet p1 = new Pet(); Upcasting and calling method: ((Pet)fido).getName() Downcasting and calling method: (Dog)
Method checked at Compile Time • Consider this: Object obj = new BankAccount(); Will the complier like this? ((BankAccount)obj). getBalance(); Why or Why not?
Which method runs determined is at RUN TIME BankAccount b1 = new CheckingAccount(100); b1.deposit(); //which method runs? b1.withdraw(); //which method runs? b1.getBalance(); //which method runs?
Bottom Line • The compiler checks method calls at compile time based on the type of OBJECT VARIABLE • When a method is overridden, which method is used (super or sub) is determined at run time by the type of OBJECT
Try This • Create BankAccount, CheckingAccount, and SavingsAccount objects • Refer to each with BankAccount variables. • Try all methods out – ask questions if the results do not make sense. Try to predict them and see if you are correct.
References Casting • Casting is done to variables NOT to objects themselves. Casting NEVER changes what an object really is “inside.” • Casting from subclass to superclass is called upcasting. • Casting from superclass to subclass is called downcasting.
Another example BankAccount b1 = new CheckingAccount(100); Is this OK? b1.printCheck(); Is this OK? b1.deposit();