Static VS. Non-Static Method

What is the difference between a static method and a non-static method?

A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.

Example:

class Foo {
int i;

public Foo(int i) {
this.i = i;
}

public static String method1() {
return "An example string that doesn't depend on i (an instance variable)";
}

public int method2() {
return this.i + 1; // Depends on i
}
}

You can call static methods like this: Foo.method1(). If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();

PHP static methods vs non-static methods/standard functions

To call a non-static method you need to instantiate the class (use the new keyword to create a new instance of the class).

When calling a static method you don't have to "new it up" but it won't have direct access to any of the non-static properties or methods. There are dozens of use-cases / scenarios where you might want to use one over the other.

To be quite honest it has never even crossed my mind to think about performance of using one over the other. If it got to a point where it made that much of a noticeable difference (and all major steps had been taken to increase efficiency) then I would imagine that either the maintenance costs of such a big application would outweigh the need for the increased efficiency or the logic behind the app is fairly flawed to begin with.


Examples for static and non-static

If I was going to use a class for the example in your question then I would use the static version as nothing in the method is reliant on other properties of the class and you then don't have to instantiate it:

Session::start_new_session()

vs

$session = new Session();

$session->start_new_session();

Also, static properties on a class will remember state that would have otherwise been lost if you were to use a non-static property and instantiation:

class Session
{
protected static $sessionStarted = false;

static function start_new_session()
{
if (!static::$sessionStarted) {
session_start();
static::$sessionStarted = true;
}
}
}

Then even if you did:

$session = new Session();

$hasStated = $session::sessionStarted;

$hasStarted would still be true.

You could even do something like:

class Session
{
protected static $sessionStarted = false;

public function __construct()
{
$this->startIfNotStarted();
}

function startIfNotStarted()
{
if (!static::$sessionStarted) {

session_start();

static::$sessionStarted = true;
}
}
}

This way you don't need to worry about starting the session yourself as it will be started when you instantiate the class and it will only happen once.

This approach wouldn't be suitable if you had something like a Person class though as the data would be different each time and you wouldn't want to use the same data in difference instantiations.

class Person
{
protected $firstname;

protected $lastname;

public function __construct($firstname, $lastname)
{
$this->firstname = $firstname;
$this->lastname = $lastname;
}

public function getFullname()
{
return "{$this->firstname} {$this->lastname}";
}
}
$person1 = new Person('John', 'Smith');
$person2 = new Person('Jane', 'Foster');

$person1->fullname(); // John Smith
$person2->fullname(); // Jane Foster

If you were to use static methods / properties for this class then you could only ever have one person

class Person
{
protected static $firstname;

protected static $lastname;

static function setName($firstname, $lastname)
{
static::$firstname = $firstname;
static::$lastname = $lastname;
}

static function getFullname()
{
return static::$firstname . ' ' . static::$lastname;
}
}
Person::setName('John', 'Smith');
Person::setName('Jane', 'Foster');

Person::getFullname(); //Jane Foster

The debates

You are probably going to see a lot of debates over which is better and what the best practices are when it comes to PHP (not just about static and not-static methods).

I wouldn't get bogged down with it though! If you find that one side makes more sense to you (and whatever you're building at the time) then go with that one. Standards and opinions change all the time in this community and half of the stuff that was a problem 5 years ago (or even less) will actually be non-issues today.

Take the Laravel framework as an example -- one of the (many) debates is that Facades are bad because they're static and make use of magic methods which is hard to test and debug. Facades are actually very easy to test and with the use of stack trace error reporting it isn't hard to debug at all. That's not to say their aren't caveats when it comes to testing static methods, but this is more to do with mocking/spying -- this answer goes into it in a little more detail.

That being said, if you find the majority of people are saying the same thing and there isn't really a debate for the other side, there is probably a reason e.g. don't use mysql_ functions or don't run queries inside a loops.

What is the difference between static methods in a Non static class and static methods in a static class?

The only difference is that static methods in a nonstatic class cannot be extension methods.


In other words, this is invalid:

class Test
{
static void getCount(this ICollection<int> collection)
{ return collection.Count; }
}

whereas this is valid:

static class Test
{
static void getCount(this ICollection<int> collection)
{ return collection.Count; }
}

Static Method of a Static Class vs. Static Method of a Non-Static Class ( C# )

Declaring a static class documents your intent for that class to be a collection of static functionality, and anyone adding instance members will get a compilation error.

A non-static class with static members usually indicates that the class is designed to be instantiated at some point. Static methods of these classes usually do one of two things:

  1. Provide a factory method for creating an instance of that type;
  2. Provide helper functionality that does not require an instance of the type;

Also, as mentioned already, extension methods can only be declared on a static class.

Static vs non-static class members

You need to think about static variables as belonging to the class, not to instances of the class.

If, in all instances of the class this variable should be identical, use a static variable.

If not, use an instance variable.

In general having public static variables is bad practice - it is a shared global resource and if you change it you need to synchronize access to it. Having global state is something you want to avoid as much as possible.

Difference between Static methods and Instance methods

The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.

However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.

You can do this to execute a static method:

MyClass.staticMethod();  // Simply refers to the class's static code

But to execute a non-static method, you must do this:

MyClass obj = new MyClass();  //Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code

On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.

Static and non-static method in one class with the same name JAVA

I want this method to be usefull with an object and also without it.
Is it possible to do something like that without creating another
method?

You will have to create another method, but you can make the non-static method call the static method, so that you do not duplicate the code and if you want to change the logic in the future you only need to do it in one place.

public class Test {
private int a;
private int b;
private int c;

public Test(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}

public String count() {
return count(a, b, c);
}

public static String count(int a1, int b1, int c1) {
String solution;
solution = Integer.toString(a1 + b1 + c1);
return solution;
}

public static void main(String[] args) {
System.out.println(Test.count(1, 2, 3));
Test t1 = new Test(1, 2, 3);
System.out.println(t1.count());
}
}


Related Topics



Leave a reply



Submit