• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

object resolution problem

 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic