Guest User

Untitled

a guest
Feb 21st, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. Class A() {
  2. Integer a1;
  3. Integer a2;
  4. }
  5.  
  6. Class B() extends A {
  7. Integer b1;
  8. }
  9.  
  10. Class A {
  11. protected Integer a1;
  12. protected Integer a2;
  13. }
  14.  
  15. Class B extends A {
  16. Integer b1;
  17. }
  18.  
  19. B b = new B();
  20. b.a1 = 3;
  21. b.a2 = 4;
  22.  
  23. A aReference = new A()
  24. aReference.a1 = 1;
  25. aReference.a2 = 2;
  26. b1 is not present in the object so can not be set.
  27.  
  28. A aReference = new B(); //reference of parent class and object of child class.
  29. aReference.a1 = 10;
  30. aReference.a2 = 20;
  31.  
  32. ((B)aReference).b1 = 30;
  33.  
  34. B bReference = new B();
  35. bReference.a1 = 10;
  36. bReference.a2 = 20;
  37. bReference.b1 = 30;
  38.  
  39. Suppose you want to modify it from inside a method of B
  40.  
  41. class B extends A{
  42. ....
  43. public void someMethod(){
  44. super.a1 = 10;
  45. super.a2 = 20;
  46. b1 = 40;
  47. }
  48. }
  49.  
  50. If you want to modify the values of the state of child from parent class
  51.  
  52. public class A{
  53.  
  54. public void someMethod(){
  55. ((B)this).b1 = 10;
  56. a1 = 20;
  57. a2 = 30;
  58. }
  59. }
  60.  
  61. class A {
  62. Integer a1=5;
  63. Integer a2=6;
  64. }
  65.  
  66. class B extends A {
  67.  
  68. }
  69.  
  70. public class Inherit {
  71.  
  72. public static void main(String[] args) {
  73.  
  74. A obj = new B(); //casting
  75. A obj2=new A();
  76.  
  77. obj.a1 = 10;
  78. obj.a2 = 12;
  79.  
  80.  
  81. System.out.println("value of a1 in class A :"+obj2.a1+" & value of a2 in class A :"+obj2.a2);
  82. System.out.println("value of a1 in class B :"+obj.a1+" & value of a2 in class B :"+obj.a2);
  83. }
  84.  
  85. }
  86.  
  87. B b = new B();
  88. b.b1 = 1;
  89.  
  90. super.a1 = 3; // must execute from B class
Add Comment
Please, Sign In to add comment