静态方法与实例方法的区别

我只是在阅读教科书上给我的课文,我不确定我是否真的理解它在说什么。它基本上告诉我,静态方法或类方法包括“修饰符”关键字 static。但我真的不知道那是什么意思?

有没有人能给我解释一下什么是静态方法或类方法?

另外,能否简单解释一下 Instance 方法是什么?

教科书上是这么写的:

静态修饰符的存在与否有着重要的实际意义。一旦 Java 处理其所属类的定义,就可以调用和执行公共类方法。实例方法不是这种情况。在调用和执行公共实例方法之前,必须创建其所属类的实例。要使用公共类方法,您只需要该类。另一方面,在使用公共实例方法之前,必须有该类的实例。

在另一个方法的定义中调用静态方法的方式根据这两个方法是否属于同一个类而有所不同。在上面的示例中,factorial 和 main 都是 MainClass 类的方法。因此,在 main 的定义中调用 factorial 只是引用了方法名“ factorial”。

243766 次浏览

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.

The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :) Same is the case with variables.

Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.

Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.)

for example:

Person.staticMethod();           //accessing static method.

for non-static method you must instantiate the class.

Person person1 = new Person();   //instantiating
person1.nonStaticMethod();       //accessing non-static method.

The behavior of an object depends on the variables and the methods of that class. When we create a class we create an object for it. For static methods, we don't require them as static methods means all the objects will have the same copy so there is no need of an object. e.g:

Myclass.get();

In instance method each object will have different behaviour so they have to call the method using the object instance. e.g:

Myclass x = new Myclass();
x.get();

If state of a method is not supposed to be changed or its not going to use any instance variables.

You want to call method without instance.

If it only works on arguments provided to it.

Utility functions are good instance of static methods. i.e math.pow(), this function is not going to change the state for different values. So it is static.

Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call. Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.

In static methods => there is no such thing as 'this'. Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).

Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.

Difference between Static methods and Instance methods

  1. Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.

  2. Static method is declared with static keyword. Instance method is not with static keyword.

  3. Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.

  4. Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.

  5. Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.

Reference : geeksforgeeks

In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.

This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.

class A {
int a;
int b;


public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}


public static returnSum(int s1, int s2){
return (s1 + s2);
}
}

In the above example, when you call add() as:

A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3


B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5


//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10


class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}

In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.

Static Methods vs Instance methods

Constructor:

const Person = function (birthYear) {
this.birthYear = birthYear;
}

Instance Method -> Available

Person.prototype.calcAge = function () {
2037 - this.birthYear);
}

Static Method -> Not available

Person.hey = function(){
console.log('Hey')
}

Class:

class PersonCl {
constructor(birthYear) {
this.birthYear = birthYear;
}


/**
* Instance Method -> Available to instances
*/
calcAge() {
console.log(2037 - this.birthYear);
}
    

/**
* Static method -> Not available to instances
*/
static hey() {
console.log('Static HEY ! ');
}
}