Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in Static Methods

 
Varalakshmi Ramanarayan
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I executed teh following piece of code I got the output
From SubClass

My Doubt is, Since main() is a static method, it can access only static members of the class.But how could it access void message() in MySubClass?
Someone please help me.

class MySuperClass {
void message() {
System.out.println("From Super Class.");
}
}

public class MySubClass extends MySuperClass {
void message() {
System.out.println("From the SubClass.");
}
public static void main(String[] args) {
MySubClass mysub = new MySubClass();
mysub.message();
}
}
 
abhishek pendkay
Ranch Hand
Posts: 184
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Varalakshmi
firstly static methods can access not-static methods only you have to specify the object on which you want to call them
for eg <object_name>.<non-Static_method>
which is exactly what you are doing in your program
and because you have overridden the superclass method you got the output from subclass
 
Rahul Shilpakar
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
message method () does not return any thing. it is just calling the method.
 
Krishna
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Varalakshmi,

A non-static class member (a variable or a method) needs an outer wrapper on which it can be called or accessed. The wrapper is nothing but an instance of the class, an object. Every object has its own set of the non-static members and handles it.

On the contrary, a static method or variable is run by the class itself(not an object). So, to access a static method, you can use either the method name only or the syntax Classname.Method()

I think that clears your doubt...

 
Varalakshmi Ramanarayan
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lots of Thanks to all three of you.
I got the point.
 
Chandu Sree
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Krishna,

If you are calling the members within the class,a static members (variables or methods) of a class can be accessed with object also.

Outside of the class you can access as you said with the class name.

Hope this would be helpful.

Thanks!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic