Skip to content
Fix Code Error

When to use static methods

March 13, 2021 by Code Error
Posted By: Anonymous

I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?

Example:

Obj x = new Obj();
x.someMethod();

…or:

Obj.someMethod(); // Is this the static way?

I’m rather confused!

Solution

One rule-of-thumb: ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.

So in a class Car you might have a method:

double convertMpgToKpl(double mpg)

…which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. But this method (which sets the efficiency of one particular Car):

void setMileage(double mpg)

…can’t be static since it’s inconceivable to call the method before any Car has been constructed.

(By the way, the converse isn’t always true: you might sometimes have a method which involves two Car objects, and still want it to be static. E.g.:

Car theMoreEfficientOf(Car c1, Car c2)

Although this could be converted to a non-static version, some would argue that since there isn’t a "privileged" choice of which Car is more important, you shouldn’t force a caller to choose one Car as the object you’ll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.

Answered By: Anonymous

Related Articles

  • Best way to extract messy HTML tables using BeautifulSoup
  • error LNK2005: ✘✘✘ already defined in…
  • How to properly do JSON API GET requests and assign…
  • How to blur the background after click on the button…
  • Enabling and disabling submit button with checkboxes
  • can't access getters in store module
  • vuetify list-item-group how to unselect the selected record
  • Python scrape JS data
  • Ember link-to throws error / does not clear screen…
  • How to change the color of the selected item in flyout menu?
  • Calculate the mean by group
  • How to parse JSON with XE2 dbxJSON
  • Ukkonen's suffix tree algorithm in plain English
  • How to use Vuex types constants with module namespace?
  • Making Make Automatically Compile Objs from Headers…
  • Azure Availability Zone ARM Config
  • Nuxt + Vuex - How do I break down a Vuex module into…
  • The 'compilation' argument must be an instance of…
  • How do I keep only the first map and when the game…
  • polymer 1.0 event firing among nested components
  • Event Snippet for Google only shows one event while…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Reference — What does this symbol mean in PHP?
  • How does Vue.js reactivity work under the hood?
  • Java verify void method calls n times with Mockito
  • Javascript change webkit style with variables
  • NullpointerException error while working with…
  • Unit test Vuex getters that depend on other getters
  • Construction and ordering of nested and template if=…
  • Search match multiple values in single field in…
  • Get the name of an object's type
  • Avoid creating new session on each axios request laravel
  • loop and eliminate unwanted lines with beautiful soup
  • mongodb group values by multiple fields
  • vuexjs getter with argument
  • Wrong response from controller JSP
  • Vuex - When to use getters and when to use state
  • Convert JavaScript string in dot notation into an…
  • Why does this Azure Resource Manager Template fail…
  • Most effective way to parse JSON Objects
  • How does the "this" keyword work?
  • Is there a way to automatically generate getters and…
  • Octave using 'for' statement to show two animations…
  • How to place object files in separate subdirectory
  • computed properties bound to getters are not…
  • Aurelia - event load / "lazy load" images
  • How do I limit the number of digits from 6 to 4 in…
  • Smart way to truncate long strings
  • The definitive guide to form-based website authentication
  • Azure CLI - az deployment group create -…
  • How to prevent scrolling the whole page?
  • How To Edit Date and Time Picker Vuejs Vuetify From…
  • How do I observe sub-property changes in Polymer?
  • Does moment.js allow me to derive a timezone…
  • Accessing getters within Vuex mutations
  • How to get and set class fields in class methods
  • How do I deal with installing peer dependencies in…
  • Binance WebSocket Order Book - depths change every time
  • JavaScript - How to have collision with character…
  • What is the copy-and-swap idiom?
  • Understanding State and Getters in Nuxt.js: Getters…
  • ./components/Avatar.tsx Error: Cannot find module…
  • .gitignore and "The following untracked working tree…
  • Peak signal detection in realtime timeseries data
  • How do I write a correct micro-benchmark in Java?
  • How to traverse the complex nested Json in C# and…
  • Angular 12 - Generating browser application bundles…
  • Issue: C compiler used for C++ in CMake | CMake + git
  • How to change color of Slider hover and active "shadow"
  • What is The Rule of Three?
  • What is a NullReferenceException, and how do I fix it?
  • Design DFA accepting binary strings divisible by a…
  • C# Get YouTube videoId from Json
  • Python JSON TypeError : list indices must be…
  • SQL query return data from multiple tables
  • Python Inserting headers for CSV file when…
  • How can I manually compile a svelte component down…
  • How does PHP 'foreach' actually work?
  • Why use getters and setters/accessors?
  • Vuetify timed universal alert component
  • How to avoid the need of writing…
  • I want to create a SQLite database like in the…
  • How to (De)serialize field from object based on…
  • What does this symbol mean in JavaScript?
  • Vue.js Vuex unit test failing , [vuex] unknown getter:
  • Mismatch Detected for 'RuntimeLibrary'
  • How to filter out getters and setters when console…
  • How to build correlation matrix plot using specified…
  • Can't upload files with Apollo-client GraphQL in…
  • Issues with registering Vuex modules, either…
  • How do I correctly clone a JavaScript object?
  • How to share "computed" methods across a Vue.js application
  • Can't access Vuex getters outside of modules
  • Errorbars and bar plots having different positions in ggplot
  • Usage of __slots__?
  • error NG6002: Appears in the NgModule.imports of…
  • How do I remove single children in a tree?
  • How to correct this error in creating Azure NSG with…
  • Create the perfect JPA entity
  • What is your most productive shortcut with Vim?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to read all files in a folder from Java?

Next Post:

Returning JSON from a PHP Script

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error