• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question regarding dynamic binding  RSS feed

 
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was given the following code the other day during an interview.



The interviewer asked me what the output would be. I said that in both cases it would be 10. She said no, in the first case it would be 5. She told me something about dynamic binding. I just ran this code and I got 5 in both cases, not just the first. I am confused. If A is an instance of B and i is defined in B to be 10, why do I get 5 in both cases?
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because variables cannot be overridden - only non-static, non-private methods can be overridden in subclasses.

In other words, the member variable i in class B does not override the i in class A.
 
Sheriff
Posts: 4289
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can get to B's i this way:

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!