my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in Static Methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in Static Methods" Watch "Doubt in Static Methods" New topic
Author

Doubt in Static Methods

Varalakshmi Ramanarayan
Ranch Hand

Joined: Oct 28, 2007
Posts: 108
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();
}
}


SCJP 5 - 87%<br />Next SCWCD
abhishek pendkay
Ranch Hand

Joined: Jan 01, 2007
Posts: 184
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


The significant problems we face cannot be solved by the same level of thinking which created them – Einstein
SCJP 1.5, SCWCD, SCBCD in the making
Rahul Shilpakar
Ranch Hand

Joined: Aug 29, 2006
Posts: 132
message method () does not return any thing. it is just calling the method.


Perform for today. Adapt for tomorrow.
Krishna
Greenhorn

Joined: Oct 31, 2007
Posts: 4
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...



Cheers,<br />Krishna
Varalakshmi Ramanarayan
Ranch Hand

Joined: Oct 28, 2007
Posts: 108
Lots of Thanks to all three of you.
I got the point.
Chandu Sree
Greenhorn

Joined: Oct 04, 2007
Posts: 22
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!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in Static Methods