Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt about inheriting static methods

 
Mala Sharma
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Suppose i have 2 classes, A(parent class) and B (child class). A has a static method C. if i want to call that static method from the public static void main(string args[]) in class B. Would i do somethig like this in class B.


because the static method belongs to the entire class. So, im thinking child class can just call that method from the parent class without instantiating it first?. I hope i haven't conufesed anyone with my wording. THanks a lot.

Mala
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can just do "C();" and it will work.
 
Mala Sharma
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, so i can call static method from the parent class in the child class just by its name?. I didn't know that. THanks a lot!
Mala
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods ARE inherited, so you can use just the name. However, you cannot override them, so they don't participate in polymorphism. Still I typically use the A.C() syntax to clarify that C() is a static method.

Layne
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to clarify:

You can't override them, but you can shadow them. This means that which method is called is determined not a run-time, but at compile time. Consider the following (rather contrived) code:


This will produce the following output:


Note what happened with the last print -- it printed Hello, World. This is because the reference type of the variable is HelloWorld, so the compiler binds the method call to HelloWorld instead of the runtime type of BonjourMonde.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic