Inheritance and Polymorphism
Inheritance and Polymorphism
3/27/13
Agenda:
3/27/13
Inheritance
Multiple inheritance:
Subclass is derived from more than one superclass. Not supported by Java. In Java, a class can only extend the definition of
3/27/13
It is the process by which one class takes the property of another class.
Inheritance
The subclass can directly access the public members of the superclass. The subclass can include additional data and method members. The subclass can override (redefine) the public methods of the superclass.
3/27/13
Polymorphism
Overloading
Two or more methods with different signatures Replacing an inherited method with another having the same signature
Overriding
3/27/13
In Java, polymorphism refers to the fact that you can have multiple methods with the same name in the same class
Overloading
3/27/13
class Test { public static void main(String args[]) { myPrint(5); myPrint(5.0); } static void myPrint(int i) { System.out.println("int i = " + i); } static void myPrint(double d) { // same name, different parameters System.out.println("double d = " + d); } } int i = 5 double d = 5.0
Overriding
class Animal { public static void main(String args[]) { Animal animal = new Animal(); Dog dog = new Dog(); animal.print(); dog.print(); } void print() { System.out.println("Superclass Animal"); } } public class Dog extends Animal { void print() { System.out.println("Subclass Dog"); } }
3/27/13
Polymorphism
You can declare a method of a class final using the keyword final. For example, the following method is final. If a method of a class is declared final, it cannot be overridden with a new definition in a derived class. In a similar manner, you can also declare a class
3/27/13
3/27/13
It is the mechanism by which a call to an overriden method is resolved at run time rather than compile time.
Abstract Classes
A class that is declared with the reserved word abstract in its heading. An abstract class can contain instance variables, constructors, access modifiers. You cannot instantiate an object of an abstract class type. You can only declare a reference variable of an abstract class type. It is through superclass reference variables that overriden methods are resolved at run time.
3/27/13
Interfaces
It contains no code, only method signature. If various implementations share only method signatures, then it is better to use interface. If we add a new method to an interface, then we have to trackdown all implementations and define new method.
3/27/13