fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.text.MessageFormat;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. public static class A {
  12. public final int a;
  13.  
  14. public A() {
  15. this.a = 0;
  16. System.out.println(
  17. MessageFormat.format("new A() constructor is called to create an instance of {0}.",
  18. getClass().getName()));
  19. }
  20.  
  21. public A(int a) {
  22. this.a = a;
  23. System.out.println(
  24. MessageFormat.format("new A(int) constructor is called to create an instance of {0}.",
  25. getClass().getName()));
  26. }
  27. }
  28.  
  29. public static class B extends A implements Serializable {
  30. public final int b;
  31.  
  32. public B(int a, int b) {
  33. super(a);
  34. this.b = b;
  35. System.out.println(
  36. MessageFormat.format("new B(int, int) constructor is called to create an instance of {0}.",
  37. getClass().getName()));
  38. }
  39.  
  40. @Override
  41. public String toString() {
  42. return "B [a=" + a + ", b=" + b + "]";
  43. }
  44.  
  45.  
  46. }
  47.  
  48. public static void main (String[] args) throws java.lang.Exception
  49. {
  50. B b1 = new B(10,20);
  51.  
  52. System.out.println(b1);
  53.  
  54. try(ObjectOutputStream oos = new ObjectOutputStream(bos)) {
  55. oos.writeObject(b1);
  56. }
  57.  
  58. ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
  59. try (ObjectInputStream ois = new ObjectInputStream(bis)) {
  60. B b2 = (B)ois.readObject();
  61. System.out.println(b2);
  62. }
  63. }
  64. }
Success #stdin #stdout 0.22s 34528KB
stdin
Standard input is empty
stdout
new A(int) constructor is called to create an instance of Ideone$B.
new B(int, int) constructor is called to create an instance of Ideone$B.
B [a=10, b=20]
new A() constructor is called to create an instance of Ideone$B.
B [a=0, b=20]