Overriding and Polymorphism
Overriding and Polymorphism
Overriding and Polymorphism
Polymorphism
• Method overriding occurs only when the names and the type
signatures of two methods across at least two classes ( i.e., a
superclass and a subclass) in a class hierarchy are identical.
• If they are not, then the two methods are simply overloaded.
• Elaborating this theme further, if the method in a subclass has a
different signature or return type than the method in the superclass,
then the subclass will have two forms of the same method.
• The superclass provides all elements that a subclass can use directly
• It also declares those methods that the subclass must implement on its
own
• This allows the subclass the flexibility to define its own method
implementations, yet still enforce a consistent interface
class Figure {
double dimension1;
double dimension2;
double area() {
System.out.println("Area of Figure is
undefined");
return 0;
}
}
class FindArea {
public static void main(String args[]){
Figure f = new Figure(10,10);
Rectangle r = new Rectangle(9,5);
Triangle t = new Triangle(10,8);
Figure fig; //reference variable
fig = r;
System.out.println("Area of rectangle is :" +
fig.area());
fig = t;
System.out.println("Area of triangle is :" +
fig.area());
fig = f;
System.out.println(fig.area());
}
}
class BigB {
public void role() {
System.out.println(" My name is BigB");
}
}
BigB v;
// Parent class reference variable can point to
// any of its CHILD class objects....
It takes an object and a type and returns true if object belongs to that
type. It returns false otherwise.
• Object defines the following methods, which means that they are
available in every object
Method Explanation
Object clone() Create a new object that is the same as the object being
cloned.
boolean equals(Object object) Determines whether one object is equal to another.
void finalize() Called before an unused object is reclaimed from the heap by
the garbage collector
final Class getClass() Obtains the class of an object at runtime
int hashCode Returns the hash code associated with the invoking object
final void notify() Resumes execution of a thread waiting on the invoking
object
final void notifyAll() Resumes execution of all waiting threads on the invoking
object.
String toString() Returns a string that describes the object.
final void wait Waits on another thread of execution.
final void wait(long milliseconds)
final void wait(long milliseconds,
long nanoseconds)
• Answer 1:
• True
• Answer 2:
• Object