Skip to content
Advertisement

How would you execute this on VSCode?

I’ve found the following code online but don’t know how to run it on IDE as I’m new to Java could you please help.

class Figure {
  void display() { System.out.print("Figure "); }
}
class Rectangle extends Figure {
  void display() { System.out.print("Rectangle "); }
  void display(String s){ System.out.print(s); } 
}
class Box extends Figure {
  void display() { System.out.print("Box ");  }
  void display(String s){ System.out.print(s); }
} 

Figure f = new Figure();
Rectangle r = new Rectangle();
Box b = new Box();
f = r;
((Figure) f).display();
f = (Figure) b;
f.display();

I tried creating a class and copy-pasting the code but couldn’t manage to produce any output. Super stuck and am still a novice. Doing it by hand I think it should output Rectangle Box.

Advertisement

Answer

Figure.java:

class Figure {
  void display() { System.out.print("Figure "); }
}

Rectangle.java:

class Rectangle extends Figure {
  void display() { System.out.print("Rectangle "); }
  void display(String s){ System.out.print(s); } 
}

Box.java:

class Box extends Figure {
  void display() { System.out.print("Box ");  }
  void display(String s){ System.out.print(s); }
} 

The rest code should be in main method and you can put main method in any one of the above .java files. I put it in Figure.java, please have a try.

enter image description here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement