Internet Technologies
1.0.0
1.0.0
  • Introduction
  • Contents
  • Practical List
  • HTML & CSS
    • Q1
    • Q2
    • Q3
    • Q4
    • Q5
  • JAVA Programs
    • Q6
    • Q7
    • Q8
    • Q9
    • Q10
    • Q11
    • Q12
  • JAVASCRIPT
    • Q13
    • Q14
    • Q15
  • JDBC
    • Q16
    • Q17
  • JSP
    • Side Note
    • Q18
    • Q19
    • Q20
    • Q21
    • Q22
    • Q23
  • End
Powered by GitBook
On this page
  • Code
  • Output
  1. JAVA Programs

Q12

Question 12

PreviousQ11NextQ13

Last updated 4 years ago

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 Insights

Created java_7.java, a new java class file and imported java.util.Scanner package to take user input for the coordinates.

To dynamic method dispatch concept the syntax or symantics used is:

Shape s = new Shape();
//s.getcoord();
//s.showcoord();
s = new Rect();
((Rect) s).showCorrd();
//newMethod((Rect) s);

giving the reference of Rect class object to the object of Shape class, the commented method above and the ((Rect) s).showCorrd() commented below does the work of giving reference. The two ways are used due to deprecation of either of one in different JDK versions.

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.

Browse Source Code
Google Colaboratory
Live Demo java_7.java
Logo
1KB
java_7.java
Download java_7.java
Image output for java_7.java