In Java:
Assume the existence of a Window class with int instance
variables width, height, xPos and yPos.
Define the method toString for the Window class. The String
representation of a Window object should be of the form "A
'width'x'height' window at ('xPos','yPos')" where the values within
the apostrophes are replaced by the actual values of the
corresponding instance variables.
For example, given a Window object whose width is 80, height is 20,
xPos is 0 and yPos is 30, toString should return "A 80x20 window at
(0,30)."
Below is your method:
/*
* Define the method toString for the Window class. The String
* representation of a Window object should be of the form
* "A 'width'x'height' window at ('xPos','yPos')" where the values within
* the apostrophes are replaced by the actual values of the corresponding
* instance variables.
*/
public String toString() {
return "A " + width + "x" + height + " window at (" + xPos + "," + yPos
+ ").";
}
Here is your complete code:
public class Window {
// instance variable
private int width;
private int height;
private int xPos;
private int yPos;
// A constructor with paramters
public Window(int width, int height, int xPos, int yPos) {
this.width = width;
this.height = height;
this.xPos = xPos;
this.yPos = yPos;
}
// default constructor
public Window() {
}
// Getters and Setters
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getxPos() {
return xPos;
}
public void setxPos(int xPos) {
this.xPos = xPos;
}
public int getyPos() {
return yPos;
}
public void setyPos(int yPos) {
this.yPos = yPos;
}
/*
* Define the method toString for the Window class. The String
* representation of a Window object should be of the form
* "A 'width'x'height' window at ('xPos','yPos')" where the values within
* the apostrophes are replaced by the actual values of the corresponding
* instance variables.
*/
public String toString() {
return "A " + width + "x" + height + " window at (" + xPos + "," + yPos
+ ").";
}
// main method to test the program
public static void main(String[] args) {
// creating an object
Window win = new Window(80, 20, 0, 30);
// printing the object, it calls toString() internally
System.out.println(win);
}
}
Output
A 80x20 window at (0,30).
Get Answers For Free
Most questions answered within 1 hours.