Win a copy of Microservices Testing (Live Project) this week in the Spring forum!
  • 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
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

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: 22662
127
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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic