• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static versus non-static

 
Thomas Hauck
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given below is a subclass SmartPhone that extends a parent class Phone:




Question: Is the reason behind the output

Call-Phone
Call-Phone

for the static methods 'call' in (parent and subclass) the following:

Each method call (lines 3 and 4) is statically bound to the class that is used to declare reference variable.

On lines 1 and 2, the base class "Phone" is being used to declare each reference variable 'phone' (line 1) and 'smartPhone' (line 2).

Because the methods are static, polymorphism does not come into play,
and each static method called (lines 3 and 4) is bound to the class (in this case the base class) used to declare the reference variable.

Please verify.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's right, yes.

To avoid the potential confusion, you should avoid doing this - calling a static method on an instance - and instead always call Phone.call() or SmartPhone.call() explicitly. But if you do call it on an instance it works exactly as you've explained.
 
Thomas Hauck
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the feedback Matthew.

This example was from a mock exam, and I wanted to verify "why" the program generates this output.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic