Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question from sarga.com

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
consider the following code
1 class Base
2 {
3 static void test() {
4 System.out.println("Base.test()");
5 }
6
7 }
8
9 public class Child extends Base {
10
11 static void test() {
12 System.out.println("Child.test()");
13 }
14
15 static public void main(String[] a) {
16 Child anObj = new Child();
17 anObj.test();
18
19 Base baseObj = anObj;
20 baseObj.test();
21 }
22 }
According to my understanding, At line # 19 , I stored child object reference as Base object reference.So,at line#20,it should call child class's test method.
But it is calling base class 's test method only.
Can somebody explain this?
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vamsi,
This has to do with early Vs. late binding. Static references are resolved at compile time, instead of runtime. Infact, the same thing happens with instance variables too, which are resolved at compile time. Just like static methods, instance variables are not polymorphic.
If the test method in Base and Child were to be non-static, then it would have displayed the polymorphic behaviour calling the Child.test() method in both the calls. Just comment out the static keyword for both test methods and see what happens!!
Good luck.

Ajith
[This message has been edited by Ajith Kallambella (edited May 15, 2000).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic