Win a copy of Kotlin for Android App Development this week in the Kotlin 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Devaka Cooray
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • salvin francis
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

overriding conecpt(please help me)  RSS feed

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am arulraj, i have one doubt in the following code:

class A
{
int x=10;
}
class B
{
int x=20;
}

A a= new B();
System.out.println("value ofx:"+a.x);

What is the output of x?

I thought it will be 20 ,but jvm gives 10...



with respect to overriding, this is ok.... (the method in class b will be called). but for variable, it provide reverse opertion.........

May i know the reason that why is pointing to X containing in class A instead of B.
 
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer lies in runtime binding. For methods except private methods, JVM at runtime determines the actual type of a reference and invokes the appropriate method on the object. For instance variable, the binding is at compile time.

Hence the VM at compile time resolves reference a as a type A and thus displays 10.
 
arulraj michealraj
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.............
 
I child proofed my house but they still get in. Distract them with this tiny ad:
Programmatically Create PDF Using Free Spire.PDF with Java
https://coderanch.com/wiki/703735/Programmatically-Create-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!