Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

static vs non static methods

Hi,

I read as follows
Instance methods ( they are usually just called methods) apply and operate on an
instance, whereas class methods apply and operate on a class or on other objects.

I wonder why using static method we cannot operate on an instance/object.
 Main method is a static method and we I can create instance of that particular class let us say ABC and call instance methods of the class right.

I have not understood what exactly mean by above sentence.

please advise
Any links resources ideas highly appreciated. Thanks in advance

Class ABC{
String color;
public static void main(String arg[]){
ABC abc=new ABC()
abc.doSomething();

}

doSomething(){
System.out.println("the color of isntance is"+color)
}
}
Avatar of dpearson
dpearson

A static method is attached to a class - not an instance of the class.

public class ABC {
    private int m_Value ;

    public static void myStaticMethod() {
       // Can't access m_Value here - because that's part of an 'instance' of ABC, not the class itself
    }

    public int myInstanceMethod() {
        // Normal (non-static) methods can access the instances they belong to
        return m_Value ;
    }
}

Does that help?

Doug
Static method and static varibles are load when the application/programing starting itself .

you can access thoess method from static method or static varibale .so we dont want to create any instances for that method or variable .

for example

Class ABC{
String color;
static String a="nsk";
public static void main(String arg[]){
ABC abc=new ABC()
abc.doSomething();
syso(a);// U can call that same calss static methid directly with out creating object
}

doSomething(){
System.out.println("the color of isntance is"+color)
syso(new ABC().a);// Here non static method so we need to create object of the class access  
}
}
SOLUTION
Avatar of Sathish David  Kumar N
Sathish David Kumar N
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@dravidnsr,
syso(new ABC().a);// Here non static method so we need to create object of the class access
That's not true, you have it the wrong way around. You are quite free to access a static variable from a non-static method. It is just that you can't do the opposite, ie. access a non-static variable from a static method.

So in your above example, you didn't need to do "new ABC().a" you could just reference "a" directly!
To access static members - (methods or variables) - only the .class bytecode file has to exist. Think static, then think "stationary, on disk in a .class file".

These static resources can then be accessed from static OR non-static contexts by instances of that class, AS WELL AS by instances of any OTHER class, (as long as the access qualifiers, (public, private, protected), permit this).

(An instance of a class does not (necessarily) have to be created for its static resources to be available to the world).
Avatar of gudii9

ASKER

A static method is attached to a class - not an instance of the class.

public class ABC {
    private int m_Value ;

    public static void myStaticMethod() {
       // Can't access m_Value here - because that's part of an 'instance' of ABC, not the class itself
    }

    public int myInstanceMethod() {
        // Normal (non-static) methods can access the instances they belong to
        return m_Value ;
    }
}

Does that help?

Doug

That make sense but in below program
Class ABC{
String color;
public static void main(String arg[]){
ABC abc=new ABC()
abc.doSomething();

}

doSomething(){
System.out.println("the color of isntance is"+color)
}
} 

Open in new window


i am able to call non static method doSomething() inside static main method right(ofcouse by creating instnace" which contradicts below statement right

Instance methods ( they are usually just called methods) apply and operate on an
instance, whereas class methods apply and operate on a class or on other objects.

Please advise
No it doesn't contradict it - because the running - i.e. the static main() caller - is a method in its own class's instance.

Static qualifiers, in a cruder than crude sense, partially circumvent the encapsulation principle - whenever you use them the code is potentially reachable (given the permission of the public, private or protected qualifiers) by any (other) class. And that "other" class, naturally, has to be resident - i.e., it itself must be an "instance", a live object.
A static method is attached to a class - not an instance of the class.

I think you are letting this statement confuse you. Yes, a static method *is* "attached" to a class - but that **doesn't** mean that it is inaccessible to instances of that or other classes - given of course the right scope qualifiers, as I said earlier.

The word "attached" above is a poor term to use. A method which returns "Hello World" as a String can be written with or without the static qualifier. With static in the signature, any instance of any class can access it. Without static, the method can only be accessed by a call into a *running* - instantiated - class object. Dump the thought of "attached", and substitute the below for the above quote :

"A static method is a method which can be called from any class, even when the class has no current instance in memory. The class accessing the static method must, quite obviously, be a running instance itself".

Finally - main() itself is static. Why? Because it is being called by a meta-instance if you like - the JVM. Hence in a suite of programmes, you theoretically need only one class with a main() method, to get the whole show on the road.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hopefully this clarifies things further, showing how static methods are called compared to instance ones -

class StaticAndInstanceExemplar {


public static void main(String[] args){

System.out.println("Hi. I'm main's static method. You need me to kick things off.\nYou can also call me from another running class instance if 

you like.\nI'm not fussy.");

StaticAndInstanceExemplar s = new StaticAndInstanceExemplar();

s.printMessage(1);
printMessage();
s.printMessage(1.1);
}


public void printMessage(int i){

System.out.println("\n\nHi.\nI'm an instance method.\nI've just been called from the static main() method,\nbut static main() was smart 

enough to instantiate the class object I am in \nbefore calling me. Why? Because I am not static,\nand so I need to be called from an 

instance.");

}


public static void printMessage(){

System.out.println("\n\nHi.\nI'm a static method.\nI've just been called from the static main() too,\nbut this time main() didn't need to make an 

object first, because I am static,\nand called on the .class.");

}


public static void printMessage(double d){

System.out.println("\n\nHi.\nI'm a static method too, but I am instead being called in an instance context, \nbecause I am a method being 

referenced by a call to its enclosing object.\nI am still static though, so as long as my access qualifier is 'public', which it is, then to call me 

again, I wouldn't need to be running inside an instantiated class object.");

}


}

Open in new window

Avatar of gudii9

ASKER

It makes more sense now.

I got out put as below

Hi. I'm main's static method. You need me to kick things off.
You can also call me from another running class instance if you like.
I'm not fussy.


Hi.
I'm an instance method.
I've just been called from the static main() method,
but static main() was smart enough to instantiate the class object I am in 
before calling me. Why? Because I am not static,
and so I need to be called from an instance.


Hi.
I'm a static method.
I've just been called from the static main() too,
but this time main() didn't need to make an object first, because I am static,
and called on the .class.


Hi.
I'm a static method too, but I am instead being called in an instance context, 
because I am a method being referenced by a call to its enclosing object.
I am still static though, so as long as my access qualifier is 'public', which it is, then to call me again, I wouldn't need to be running inside an instantiated class object.

Open in new window


printMessage();
s.printMessage(1.1);

Open in new window


How calling static method in above two approaches is different or similar and which on is preferred. please advise
Static is static, whether referenced through a class instance object, or on the class itself. Both are isotopes of the same thing. The implementable complexion is determined by the access qualifiers, (public, private, protected) - such that if you make printMessage() private  static void instead of public static void, (for example), you get a method which is only callable by its own class and instances thereof.
Avatar of gudii9

ASKER

so Static is different from 'access modifiers' public, private, protected. What kind of modifier static is called as?

Are both of below statements means the same in this case?

printMessage();
and
StaticAndInstanceExemplar.printMessage();

 please advise
Yes, they mean the same thing effectively.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
but if you are need to call that method from somewhere outside that class, then only the second alternative would work

. . . yes, but not the complete picture . . . because you can also call the method from outside the class, by calling it on an instance of the class - so long as it is 'public' (or 'protected' if it's from another package member class).
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial