Solved

static vs non static methods

Posted on 2013-11-21
17
574 Views
Last Modified: 2013-12-02
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
Comment
Question by:gudii9
  • 8
  • 3
  • 2
  • +2
17 Comments
 
LVL 26

Expert Comment

by:dpearson
Comment Utility
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
 
LVL 20

Expert Comment

by:Sathish David Kumar N
Comment Utility
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
 
LVL 20

Assisted Solution

by:Sathish David Kumar N
Sathish David  Kumar N earned 125 total points
Comment Utility
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
 
LVL 35

Expert Comment

by:mccarl
Comment Utility
@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
 
LVL 16

Expert Comment

by:krakatoa
Comment Utility
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
 
LVL 7

Author Comment

by:gudii9
Comment Utility
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
 
LVL 16

Expert Comment

by:krakatoa
Comment Utility
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
 
LVL 16

Expert Comment

by:krakatoa
Comment Utility
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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 26

Assisted Solution

by:dpearson
dpearson earned 125 total points
Comment Utility
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
 
LVL 16

Expert Comment

by:krakatoa
Comment Utility
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
 
LVL 7

Author Comment

by:gudii9
Comment Utility
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
 
LVL 16

Expert Comment

by:krakatoa
Comment Utility
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
 
LVL 7

Author Comment

by:gudii9
Comment Utility
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
 
LVL 16

Expert Comment

by:krakatoa
Comment Utility
Yes, they mean the same thing effectively.
0
 
LVL 35

Assisted Solution

by:mccarl
mccarl earned 125 total points
Comment Utility
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
 
LVL 16

Expert Comment

by:krakatoa
Comment Utility
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
 
LVL 16

Accepted Solution

by:
krakatoa earned 125 total points
Comment Utility
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

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now