Relationships and Dynamic Method Dispatch in Java: Instructor
Relationships and Dynamic Method Dispatch in Java: Instructor
The compiler and Java virtual machine (JVM) will do a lot of work for you
when you use inheritance, you can also get at the functionality of
inheritance when you use composition.
IS-A Relationships in Java
4
It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is
a Vehicle etc. Inheritance is uni-directional. For example, House is a Building.
But Building is not a House.
It is a key point to note that you can easily identify the IS-A relationship.
Wherever you see an extends keyword or implements keyword in a class
declaration, then this class is said to have IS-A relationship.
HAS-A Relationships in Java
5
Class Car
IS-A
package relationships;
class Car
{
// Methods implementation and class/Instance members
private String color;
private int maxSpeed;
public void carInfo()
{ System.out.println("Car Color= "+color + " Max Speed= " + maxSpeed); } public
void setColor(String color)
{ this.color = color; }
public void setMaxSpeed(int maxSpeed)
{ this.maxSpeed = maxSpeed; }
}
IS-A and HAS-A Relationship (Example Slide-2)
8
package relationships;
public class Engine
{
public void start()
{ System.out.println("Engine Started:"); }
public void stop()
{ System.out.println("Engine Stopped:");}
}
IS-A and HAS-A Relationship (Example Slide-4)
10
package relationships;
public class RelationsDemo
{
public static void main(String[] args)
{
Honda myHonda = new Honda();
myHonda.setColor("RED");
myHonda.setMaxSpeed(180);
myHonda.carInfo();
myHonda.HondaStartDemo();
}
}
Dynamic Method Dispatch (1/3)
11
Important Points?
The program creates one superclass called A and it’s two subclasses B and C.
These subclasses overrides m1( ) method.
Dynamic Method Dispatch (Example Explanation)
17
Dynamic Method Dispatch (Example Explanation)
18
Dynamic Method Dispatch (Advantages)
19
2.It allows a class to specify methods that will be common to all of its derivatives,
while allowing subclasses to define the specific implementation of some or all of
those methods.
3. It also allow subclasses to add its specific methods subclasses to define the
specific implementation of some.
References
20
THANK YOU