Java - Problems with understanding inheritance -


i facing problems inheritance in java. can't understand why following 2 programs have outputs! me? :)

1)

public class {     int foo() {         return 1;     } }  public class b extends {     int foo() {         return 2;     } }  public class c extends b {     int bar(a a) {         return a.foo();     } }  c x = new c();   system.out.println(x.bar(x));  // output:2 

2)

public class {     int e=1; }  public class b extends {     int e=2; }  public class c extends b {     int bar(a a){         return a.e;     } }  c x= new c(); system.out.println(x.bar(x));  // output:1 

in both cases, you're passing in object of type c print function. bar function asks object of type a, it's still acceptable pass in object of type c since subclass of a. first of all, it's important keep in mind a.foo() , a.e being called on c object.

so happening in both cases it's searching lowest attribute or method in list. here simplified version of java doing in part 1:

  1. hey, you've passed in object of type c bar method! let's call foo method.
  2. whoops! c doesn't have foo method! let's take next step b class see if has foo method.
  3. yay! b has foo method, let's call it. no need work our way a class because we've found need in b.

it's understanding parameter downcast a c. exact same sort of logic used in part 2. notices object of type c passed in, gets e attribute object b since lowest class in hierarchy contains attribute.

hopefully answers question!


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -