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

Overriding static methods

 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following example:



Outputs the following:



I understand why the Parent's get1 method gets called on both instances i.e. because static methods are not overridden. What i don't understand is why the output is different if i override the get() method as shown below:



With the overridden get() method, the output is



Why does the version with the overridden get() method not call the Parent's get1() method for the object using the Parent reference (i.e. Parent p = new Child())?

Thanks


 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
consider the below code


if you call this method on a reference which points to his sub class object then it the method is static it process the reference's method else sub class's method. and in your second case get method of sub class called[because get() is an instance method] and then it execute its own static get method[this.get1()]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic