Inheritance Lakshmish Ramaswamy
Multiple Inheritance A class being derived from more than one base class Ex: A StudentEmployee Class being derived both from Student and Employee Some OO languages (ex: C++) support multiple inheritance Java does not allow multiple inheritance
Issues with Multiple Inheritance Does StudentEmployee get two copies of name, address and phone number? If StudentEmployee does not override toString method, which implementation would be used? If a method is declared to be final in one base class and not in the other, would the StudentEmployee be allowed to override the method?
Interface Alternative to multiple inheritance The ultimate abstract class Consists only of public abstract methods & public static final fields No implementation of any method Class providing definitions of all abstract methods is said to implement the interface Multiple interfaces do not suffer from same problems as multiple inheritance Class can implement multiple interfaces but extend from a single class
Specifying Interface Similar to a class declaration but uses the keyword interface Lists methods that need to be implemented Class implementing an interface should do two things Declare that it implements the interface using “implements” Provide implementations of at least one method declared in interface A method implementing an interface may remain abstract
Example of Interface
Example of Implementing Class
Multiple Interfaces Java allows multiple interfaces List all the interfaces a class is implementing Provide implementations of all methods in all interfaces public class X implements a, b { … }
Interfaces as Abstract Classes IS-A relationship holds instanceof operator can be used to test type compatibility Implementing class cannot reduce the visibility of methods Implementing class may not add checked exceptions to throws list In case of multiple interfaces implementation can throw exception that is listed in all interfaces
Interfaces as Abstract Classes Class implementing an interface should override with the exact signature Cannot implement two interfaces with same signature but different return types Class that partially implements an interface should be declared abstract Interfaces can extend other interfaces
Fundamental Inheritance in Java If class does not explicitly extend another class, it implicitly extends Object class Object contains several methods Object is not abstract class All methods are implemented toString, equals and hashCode are some of the important methods