Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

object resolution problem

 
Indravadan T Patel
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Super {
int a = f();
int f() {
return 1;
}
}

class Sub extends Super{
int b = 2;
int f() {
return b;
}
}

public class Test1 {
public static void main(String[] args) {
Super sup = new Sub();
System.out.println(sup.a);
System.out.println(sup.f());
}
}

I get the output of that program : 0 2
but i can't understand why that happen?
 
Paresh Joshi
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Indravadan ...

i hope you know that in java

Super sup = new Sub();

here whatever you invoke using "sup" it will refer to Sub's method not a Super's.

becuase sup ------> Object Of Sub

for that reason you're getting o/p as 2

and about "0" you're initializing it by calling method ... but at that time compiler doesnt know about that method.
so by default members of classes in java intializes to its default value.

(i.e. 0 for integer)
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Paresh Joshi:
and about "0" you're initializing it by calling method ... but at that time compiler doesnt know about that method.
so by default members of classes in java intializes to its default value.

(i.e. 0 for integer)[/QB]

Actually, the compiler does now about that method.

Here's the order of execution:
1) a = f(); However, f returns b because it uses the actual implementation of f() of the object, not the reference. The object is a Sub. b has not been initialized so it is 0. a will become 0.
2) b = 2;
3) a is retrieved. It is still 0 after step 1.
4) f() is called on the sub, which returns b which is 2.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic