Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 594
  • Last Modified:

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)
}
}
0
gudii9
Asked:
gudii9
  • 8
  • 3
  • 2
  • +2
4 Solutions
 
dpearsonCommented:
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
0
 
Sathish David Kumar NArchitectCommented:
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  
}
}
0
 
Sathish David Kumar NArchitectCommented:
Class ABC{
String color;

public static x(){

syso("Nsk");
}

}
}

classDEF{
public static xyz(){


syso(ABC.a);// U can directly call the object with class name with out creating instance
}

}
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
@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!
0
 
krakatoaCommented:
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).
0
 
gudii9Author Commented:
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
0
 
krakatoaCommented:
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.
0
 
krakatoaCommented:
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.
0
 
dpearsonCommented:
To go back to your example:

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


a) ABC.main is a static method.  That method can only be called as:

"ABC.main" <-- Note how you use the class name here

public static void main() {
    // Compiler error - can't access 'color' since it's a instance variable (not static)
   System.out.println("the color of isntance is"+color)
}

b) doSomething is an instance method.  That method can only be called on an instance of ABC:

abc.doSomething();

public void doSomething() {
    // Can access 'color' as this code is executing inside a specific instance of ABC.
   System.out.println("the color of isntance is"+color)
}

c) Inside any method, you can call to any other public method in the system.
    So inside a static method, you can call instance methods (as long as you can access the objects), other static methods etc.

public class Class1 {
  public static void myStaticMethod() {
      Class1.myOtherStaticMethod() ; // Fine

      Class2 a = new Class2() ;
      a.myOtherInstanceMethod() ;  // Fine - but I needed an instance of Class2 first

      this.myInstanceMethod() ; // Nope - not allowed.  There is no "this" for a static method - no instance since it's a class method
  }

  public void myInstanceMethod() {
     Class1.myOtherStaticMethod() ; // Fine

      Class2 a = new Class2() ;
      a.myOtherInstanceMethod() ;  // Fine - but I needed an instance of Class2 first

      this.myInstanceMethod() ; // Fine since we're calling it inside an instance of Class1
  }
}

I hope that helps clear things up.

Doug
0
 
krakatoaCommented:
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

0
 
gudii9Author Commented:
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
0
 
krakatoaCommented:
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.
0
 
gudii9Author Commented:
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
0
 
krakatoaCommented:
Yes, they mean the same thing effectively.
0
 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Are both of below statements means the same in this case?

printMessage();
and
StaticAndInstanceExemplar.printMessage();

 please advise
Just to make it 100% clear, they are the same when used from within the StaticAndInstanceExemplar class, but if you are need to call that method from somewhere outside that class, then only the second alternative would work.
0
 
krakatoaCommented:
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).
0
 
krakatoaCommented:
Inside the class :

printmessage(); ,   s.printMessage();  ,  and  StaticAndInstanceExemplar.printMessage();

are all ok.

Outside the class :

s.printMessage() and StaticAndInstanceExemplar.printMessage(); are ok as long as the access modifier permits.


---------------

(For completeness sake, I should have said that both 'public' *and* 'protected' would qualify a call from another package member).
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 8
  • 3
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now