Two Laptop Bag*
The moose likes Java in General and the fly likes Reason behind dynamic lookup Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Reason behind dynamic lookup" Watch "Reason behind dynamic lookup" New topic
Author

Reason behind dynamic lookup

Vijay Gade
Ranch Hand

Joined: Jul 04, 2005
Posts: 81
Hello,

A very simple code:
----------------------------------------------------

public class DynamicLookup { //considering this to be Line 1
public static void main(String[] args) {
A a = new C();
B b = (B)a;
System.out.println("b.a1=" + b.a1); //Line 5
b.func(); //Line 6
}
}
class A {
int a1 = 10;
void func() {System.out.println("A");}
}
class B extends A {
int a1 = 20;
void func() {System.out.println("B");}
}
class C extends B {
int a1 = 30;
void func() {System.out.println("C");}
}
----------------------------------------------------

Question:

I know that Line 5 would print 20, and Line 6 would print C. But why? Why is it that the member variables (and of course static methods) will be given a "CLASS TYPE OF OBJECT" preference verses the non-static member functions will be given "THE OBJECT THAT IS BEING POINTED TO" preference? What happens inside at the C++ level?

Thanks in advance,

-Vijay
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

Sections 15.11 and 15.12 of the Java� Language Specification define the behavior you are witnessing.
[ July 06, 2005: Message edited by: Steve Morrow ]
Vijay Gade
Ranch Hand

Joined: Jul 04, 2005
Posts: 81
Thank you Steve.
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

You're welcome. And the JLS may seem somewhat ambiguous or poorly written in sections. Be sure to let us know if there are any parts that are confusing.

Cheers!
 
Consider Paul's rocket mass heater.
 
subject: Reason behind dynamic lookup
 
Similar Threads
pass by value?
Are my answers correct ?
Khalid Mock Exam
JQplus
Question from Khalid's mock test