Home / Programs / Design a class to overload a function polygon() as follows:
Programming Example

Design a class to overload a function polygon() as follows:

👁 145 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

Design a class to overload a function polygon() as follows:

  1. void polygon(int n, char ch) — with one integer and one character type argument to draw a filled square of side n using the character stored in ch.
  2. void polygon(int x, int y) — with two integer arguments that draws a filled rectangle of length x and breadth y, using the symbol '@'.
  3. void polygon() — with no argument that draws a filled triangle shown below:

Example:

  1. Input value of n=2, ch = 'O'
    Output:
    OO
    OO
  2. Input value of x = 2, y = 5
    Output:
    @@@@@
    @@@@@
  3. Output:
    *
    **
    ***

Program Code

public class KboatPolygon
{
    public void polygon(int n, char ch) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                System.out.print(ch);
            }
            System.out.println();
        }
    }
    
    public void polygon(int x, int y) {
        for (int i = 1; i <= x; i++) {
            for (int j = 1; j <= y; j++) {
                System.out.print('@');
            }
            System.out.println();
        }
    }
    
    public void polygon() {
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print('*');
            }
            System.out.println();
        }
    }
    
    public static void main(String args[]) {
        KboatPolygon obj = new KboatPolygon();
        obj.polygon(2, 'o');
        System.out.println();
        obj.polygon(2, 5);
        System.out.println();
        obj.polygon();
    }
}

Output

oo
oo

@@@@@
@@@@@

*
**
***
Press any key to continue . . .

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.