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:
- hey, you've passed in object of type
cbarmethod! let's callfoomethod. - whoops!
cdoesn't havefoomethod! let's take next stepbclass see if hasfoomethod. - yay!
bhasfoomethod, let's call it. no need work our wayaclass 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
Post a Comment