wood burning stoves 2.0*
The moose likes Java in General and the fly likes object resolution problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "object resolution problem" Watch "object resolution problem" New topic
Author

object resolution problem

Indravadan T Patel
Greenhorn

Joined: Sep 09, 2007
Posts: 29
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

Joined: Jul 19, 2007
Posts: 5
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

Joined: Oct 27, 2005
Posts: 19785
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: object resolution problem