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
c
bar
method! let's callfoo
method. - whoops!
c
doesn't havefoo
method! let's take next stepb
class see if hasfoo
method. - yay!
b
hasfoo
method, let's call it. no need work our waya
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
Post a Comment