Guest User

Untitled

a guest
Jan 22nd, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. public class A{
  2. public int intVal = 1;
  3. public void identifyClass()
  4. {
  5. System.out.println("I am class A");
  6. }
  7. }
  8.  
  9. public class B extends A
  10. {
  11. public int intVal = 2;
  12. public void identifyClass()
  13. {
  14. System.out.println("I am class B");
  15. }
  16. }
  17.  
  18. public class mainClass
  19. {
  20. public static void main(String [] args)
  21. {
  22. A a = new A();
  23. B b = new B();
  24. A aRef;
  25. aRef = a;
  26. System.out.println(aRef.intVal);
  27. aRef.identifyClass();
  28. aRef = b;
  29. System.out.println(aRef.intVal);
  30. aRef.identifyClass();
  31. }
  32. }
  33.  
  34. 1
  35. I am class A
  36. 1
  37. I am class B
  38.  
  39. OverRiding Concept in Java
  40. Functions will override depends on object type and variables will accessed on reference type.
  41.  
  42. 1. Override Function: In this case suppose a parent and child class both have same name of function with own definition. But which function will execute it depends on object type not on reference type on run time.
  43.  
  44. For e.g.:
  45. Parent parent=new Child();
  46. parent.behaviour();
  47. //in that case parent is a reference of Parent class but holds the object of Child Class so thats why Parent class function will call in that case.
  48.  
  49. Child child=new Child();
  50. child.behaviour();
  51. //in that case child holds the object of Child Class so thats why Child class function will call in that case.
  52.  
  53. Parent parent=new Parent();
  54. parent.behaviour();
  55. //in that case parent holds the object of Parent Class so thats why Parent class function will call in that case.
  56.  
  57. 2. Override Variable: Java supports overloaded variables. But actually these are two different variables with same name. One in parent class ad second in child class. And both variable can be either of same datatype or different.
  58.  
  59. When you trying to access the variable, it depends on reference type object not depends on object type.
  60.  
  61. For e.g.:
  62. Parent parent=new Child();
  63. System.out.println(parent.state);
  64.  
  65. //in that case reference type is Parent so Parent class variable is accessed not Child class variable.
  66.  
  67. Child child=new Child();
  68. System.out.println(child.state);
  69.  
  70. //in that case reference type is Child so Child class variable is accessed not Parent class variable.
  71.  
  72. Parent parent=new Parent();
  73. System.out.println(parent.state);
  74.  
  75. //in that case reference type is Parent so Parent class variable is accessed not Child class variable.
Add Comment
Please, Sign In to add comment