• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructor and subclasses

 
Serge Plourde
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I made that question from an idea I got in reading Thinking in Java (p.35)
What would be the result in trying to compile then run the following program?
class ShapeArray
{
public static void main (String args[])
{
XShape myShape = new XShape("1");
XCircle myCircle = new XCircle("2");
XRectangle myRectangle = new XRectangle("3");
XShape [] shapes = { myShape, myCircle, myRectangle };
for (int i = 0; i < 3; i++)
{
shapes[i].draw();
}
}
}
class XShape
{
String shapeId;
/*
XShape()
{
System.out.println("Shape null constructor");
}
*/
XShape(String anId)
{
shapeId = anId;
System.out.println("Shape " + shapeId + " has been created");
}
void draw()
{
System.out.println("draw method of Shape " + shapeId + " invoked");
}
void erase()
{
System.out.println("erase method of Shape " + shapeId + " invoked");
}
}
class XCircle extends XShape
{
XCircle(String anId)
{
shapeId = anId;
System.out.println("Circle " + shapeId + " has been created");
}
void draw()
{
System.out.println("draw method of Circle " + shapeId + " invoked");
}
void erase()
{
System.out.println("erase method of Circle " + shapeId + " invoked");
}
}
class XRectangle extends XShape
{
XRectangle(String anId)
{
shapeId = anId;
System.out.println("Rectangle " + shapeId + " has been created");
}
void draw()
{
System.out.println("draw method of Rectangle " + shapeId + " invoked");
}
void erase()
{
System.out.println("erase method of Rectange " + shapeId + " invoked");
}
}
a) compiles and runs fine
b) compiles but gives a runtime error
c) gives a compile error (which one?)
d) prints:
Shape 1 has been created
Draw method of Shape 1
Shape 2 has been created
Draw method of Shape 2
Shape 3 has been created
Draw method of Shape 3
e)The following lines are displayed:
Shape 1 has been created
Shape 2 has been created
Circle 2 has been created
Shape 3 has been created
Rectangle 3 has been created
draw method of Shape 1 invoked
draw method of Circle 2 invoked
draw method of Rectangle 3 invoked
 
Serge Plourde
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If, and only if, the program does not compile, what statement would you have to put in the constructor of class XCircle, and of Class XRectangle to make it work? (one additional statement only per constructor)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic