Results 1 to 4 of 4
purpose of static methods and variables ?
This is a discussion on purpose of static methods and variables ? within the Programming forums, part of the Web Designing & Development category; Hello Dear, Please Tell Me What is the purpose of static methods and variables ?...
- 09-27-2019, 11:58 AM #1
- Join Date
- Feb 2018
- Posts
- 94
purpose of static methods and variables ?
Hello Dear,
Please Tell Me What is the purpose of static methods and variables ?
- 11-15-2019, 12:30 PM #2
- Join Date
- Jan 2018
- Location
- PUNE
- Posts
- 281
Re: purpose of static methods and variables ?
If you apply static keyword with any method, it is known as static method. A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class. static method can access static data member and can change the value of it.
- 08-05-2020, 06:54 AM #3
- Join Date
- Aug 2020
- Location
- Ho Chi Minh
- Posts
- 2
Re: purpose of static methods and variables ?
i'm waiting for the comments from others
- 12-03-2020, 05:15 PM #4
- Join Date
- Nov 2020
- Posts
- 11
Re: purpose of static methods and variables ?
The closer answers were given by Saravanan P, Bharti Sihol, and Deeksha Puri. But most answers given lack the explanation of the PURPOSE of using static variables and methods. To get to the purpose, we must answer WHY should we use static modifier. Saravanan stated that “static variable can be used to refer the common property of all objects.” The same goes for methods (behaviors). We use static methods when we want certain behaviors of a class to be the same across all instances of a class. What does that mean? Deeksha and Bharti both stated that static class members are shareable across all instances of the same class.
To illustrate, consider a class that models a Car. Cars have engines. But no two cars share the same engine (simultaneously). This means that each car has an engine that belongs to it exclusively. Therefore, an engine in a Car class would be a non-static attribute of the class. HOWEVER, the brand name of a car is shared across all instances of a class. In this case, brandName (i.e. Chevrolet) should be shared across all Car instances. Now, here’s the WHY you want to do this. Suppose tomorrow Chevrolet is bought by Ford. By making the brandName shareable (static) across all instances of Car, every instance of Car can be rebranded to Ford by making a single change. Because this is a shareable attribute, all instances receive the change without having to go to each individual instance to make the same change.