In: Computer Science
Write the code to create a class Square implementing the interface Figure with constructor to initialize with a size and toString method. Write another class SquareUser that creates and array of Squares and initializing with sides 1, 2,3, 4 and 5. Also write the code to call the toString method of squares in a loop to print the string for all squares in the array.
Explanation:
Here is the class Square implemention the interface Figure with the area method declaration and the size variable.
In the square class, the constructor is defined to initialise the size variable.
ALso, the SquareUser class is there which creates an array of Square class objects and then calls the toString method for each of the object
Code:
interface Figure
{
int size=0;
public int area();
}
class Square implements Figure
{
int size;
Square(int s)
{
size = s;
}
public String toString()
{
return "This is a Square with size "+size;
}
public int area()
{
return size*size;
}
}
public class SquareUser
{
public static void main(String[] args) {
Square arr[] = new Square[5];
arr[0] = new Square(1);
arr[1] = new Square(2);
arr[2] = new Square(3);
arr[3] = new Square(4);
arr[4] = new Square(5);
for(int i=0; i<arr.length;
i++)
{
System.out.println(arr[i]);
}
}
}
Output:
PLEASE UPVOTE IF YOU FOUND THIS HELPFUL!
PLEASE COMMENT IF YOU NEED ANY HELP!