Object Oriented Programing: Name System Id Instuctor Program Section
Object Oriented Programing: Name System Id Instuctor Program Section
SECTION II -A
Assignment #2
Q.1
Create a Java Class “Figure”. Class Figure takes two data members as
dim 1 and dim2 of double datatype. And a Constructor to initialize these
data members. Create a member function “Area ()” in figure class. Create
two sub classes Triangle and rectangle. Have the same members function
as Area (). That calculate the area for rectangle and triangle. Write
another class Figure Areas which test these classes by making objects and
display areas for different figures respectively.
PROGRAM
import java.util.Scanner;
Q.2
What do you understand the concept dynamic method
dispatch? Explain with example
Dynamic Method Dispatch
Dynamic method dispatch is the mechanism in which a call to an overridden method
is resolved at run time instead of compile time. This is an important concept because
of how Java implements run-time polymorphism.
Advantages of dynamic method dispatch
1. It allows Java to support overriding of methods, which are important for
runtime polymorphism.
2. It allows a class to define methods that will be shared by all its derived classes,
while also allowing these sub-classes to define their specific
implementation of a few or all of those methods.
3. It allows subclasses to incorporate their own methods and define their
implementation.
Example
class Phone{
public void showTime(){
System.out.println("Time is 8 am");
}
public void on(){
System.out.println("Turning on Phone...");
}
}
class SmartPhone extends Phone{
public void music(){
System.out.println("Playing music...");
}
public void on(){
System.out.println("Turning on SmartPhone...");
}
}
public class CWH {
public static void main(String[] args) {
Phone obj = new SmartPhone();
obj.showTime();
obj.on();
}
}
Output