code_junkie

Inheritance in Java - creating an object of the subclass invokes also the constructor of the superclass. Why exactly

Nov 13th, 2011
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. public class A {
  2. public A() {
  3. System.out.println("Hi!");
  4. }
  5. }
  6.  
  7.  
  8. public class B extends A {
  9. public B() {
  10. System.out.println("Bye!");
  11. }
  12.  
  13. public static void main(String[] args) {
  14. B b = new B();
  15. }
  16. }
  17.  
  18. public class B extends A {
  19. public B() {
  20. super();
  21. System.out.println("Bye!");
  22. }
  23. ...
  24. }
  25.  
  26. class Q {
  27. int i;
  28. public Q() {
  29. // set default value
  30. i= 99;
  31. }
  32. }
  33.  
  34. class Z extends Q {
  35. public Z() {
  36. }
  37. }
  38.  
  39. public class A {
  40. public A() {
  41. x = 1;
  42. }
  43. private int x;
  44. public int getX() {
  45. return x;
  46. }
  47. }
  48.  
  49.  
  50. public class B extends A {
  51. public B() {
  52. }
  53.  
  54. public static void main(String[] args) {
  55. B b = new B();
  56. System.out.println(b.getX()); // should print 1
  57. }
  58. }
Add Comment
Please, Sign In to add comment