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

confuse for static method

 
Fu Dong Jia
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi!
look at the follow codes:

Running this code produces the output:
a a a

why the second output is "a",but not "b"?
other question: can static method and variable be inheritd?why?
thanks in advance!
 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
your second question : static methods variables ,not can be inherited but not overridden,insteads redefined.
Sbout 1st question :
Animal []x={new Dog(),new Animal()};
when method is called, which version will be called is decided at compile time,since at compile time ,we have no objject-type info,so its based on refernece type only.
so when x.method() is called, no matter what is runtime of x,but compile time type,reference type is Animal.
you read Polymorphism chapter carefully.This topic is ofcourse bit confusing.
 
Fu Dong Jia
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lucky J Verma,thanks for help.
As you say "when method is called, which version will be called is decided at compile time." should this rule fit for static method only?
I have remember,for nomal method(no-static),which method can be called decided on compile time(variable type),and which method can be called is dicided at run time(object type).
 
Gaurav Gambhir
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In case of overloading
Which overloaded version of the method to call is based on reference type of the argument passed at compile time

In case of overriding
Which overridden version of the method to call is decided at runtime based on object type

In the above example we have two static methods with same signature in parent and child class, but static methods are not overridden, and they are associated with the class so which method to call will be based to reference type
 
aslika bahini
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




actually, if you closely look these two methods.
you can find difference in
static void doStuff() (in Animal class..uppercase S)
static void dostuff() (in Dog class..lowercase s)

It's a redefinition not an override

regards
samura
 
Collins Mbianda
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi !!!

This article could be of interest:

Overriding Vs Hiding
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic