Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance Lakshmish Ramaswamy.

Similar presentations


Presentation on theme: "Inheritance Lakshmish Ramaswamy."— Presentation transcript:

1 Inheritance Lakshmish Ramaswamy

2 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

3 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?

4 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

5 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

6 Example of Interface

7 Example of Implementing Class

8 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 { }

9 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

10 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

11 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


Download ppt "Inheritance Lakshmish Ramaswamy."

Similar presentations


Ads by Google