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 Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.

📌 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();
    }
}
                        

🖥 Program Output

oo
oo

@@@@@
@@@@@

*
**
***
Press any key to continue . . .
                            
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.