fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. GenericObject o;
  13.  
  14. o = new Object1(10, 10);
  15. o.wh();
  16. System.out.println(o.w); // Output: 3 (ok)
  17. System.out.println(o.h); // Output: 10 (ok)
  18.  
  19. o = new Object2(10, 10);
  20. o.wh();
  21. System.out.println(o.w); // Output: 7 (ok)
  22. System.out.println(o.h); // Output: 4 (ok)
  23.  
  24. String inputFromUser = "1";
  25.  
  26. // o = new Object + inputFromUser + (10, 10);
  27. /*I know that is an absurd, just to illustrate...
  28. if polymorphism can solve this problem, I thik it's the best option. So how use it here?
  29. I don't wanna use ifs or switchs, I will use more than 300 classes*/
  30.  
  31. Class<?> typeFromUser = Class.forName("Object" + inputFromUser);
  32. java.lang.reflect.Constructor<?> constructor = typeFromUser.getDeclaredConstructor(Integer.TYPE, Integer.TYPE);
  33. Object obj = constructor.newInstance(10, 10);
  34. o = (GenericObject) obj;
  35.  
  36. o.wh();
  37. System.out.println(o.w); // Output: 3 (that's what I wanna obtain)
  38. System.out.println(o.h); // Output: 10 (that's what I wanna obtain)
  39. }
  40. }
  41.  
  42. abstract class GenericObject {
  43. int w, h, x, y;
  44. GenericObject (int x, int y) {
  45. this.x = x;
  46. this.y = y;
  47. }
  48. public abstract void wh();
  49. }
  50. class Object1 extends GenericObject{
  51. Object1 (int x, int y) {
  52. super(x, y);
  53. }
  54. @Override
  55. public void wh () {
  56. w = 3;
  57. h = 10;
  58. }
  59. }
  60. class Object2 extends GenericObject{
  61. Object2 (int x, int y) {
  62. super(x, y);
  63. }
  64. @Override
  65. public void wh () {
  66. w = 7;
  67. h = 4;
  68. }
  69. }
Success #stdin #stdout 0.1s 320512KB
stdin
Standard input is empty
stdout
3
10
7
4
3
10