Q12
Question 12
Create a base class called Shape. It should contain 2 methods getcoord() and showcorrd () to accept X and Y coordinates and to display the same respectively. Create a sub class called Rect. It should also contain a method to display the length and breadth of the rectangle called showCorrd(). In main method, execute the showCorrd() method of the Rect class by applying the dynamic method dispatch concept.
Code
/**
*Solution for Ans. 11
* @author Jatin Kamboj 8647
*/
import java.util.Scanner;
// Shape Class
class Shape {
int x;
int y;
void getcoord() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter coordinates of (x,y): ");
x = sc.nextInt();
y = sc.nextInt();
}
void showcoord() {
System.out.print("Coordinates are: (" + x + ", "
+ y + ")");
}
}
class Rect extends Shape {
int length = 10;
int breadth = 20;
void showCorrd() {
System.out.println("\nLength of Rectangle is : "
+ length + " and Breadth is : " + breadth);
}
}
public class java_7 {
public static void main(String[] args) {
Shape s = new Shape();
System.out.println("\n\t-- This program will" +
" demonstrate dynamic method dispatch concept." +
" --\n");
s.getcoord();
s.showcoord();
s = new Rect();
//((Rect) s).showCorrd();
newMethod((Rect) s);
}
private static void newMethod(Rect s) {
s.showCorrd();
}
}
Output

Try or Test The Corresponding Code Here
The above notebook runs on cloud, make sure to run the first cell of the notebook to set-up JDK and JRE on the cloud machine.
Last updated