+7

Why it is convenient to make objects instead of methods static?

3/24/2019 6:59:41 PM

Hugo Hector Ramirezz

37 Answers

New Answer

+17

David Carroll 👍 Thank you very much! 👏👏🍻

+15

Part 2 of 5: To dig deeper into this understanding, lets consider the following example class representing a Course (using pseudo code): class Course /**** Instance Properties ****/ int CourseId; string Name; DateTime DateCreated; DateTime DateLastModified; CourseModules Modules; /**** Instance Methods ****/ /* Saves current instance * and returns a courseId */ int Save(){...} /**** Static Properties ****/ static int LoadedCoursesCount; /**** Static Methods ****/ /* Loads from JSON string */ static Course Load(string json){...} /* Loads from database. */ static Course Load(int courseId){...} /* Saves JSON to database * and returns a courseId. */ static int Save(string json){...} /* Validates a Course instance can be * loaded from the given JSON string. */ static bool Validate(string json){...}

+14

Part 1 of 5: I'm copying Morpheus, HonFu and Gordon because I've seen other good OOP related questions and thought they would be interested in my 5 part answer here. 😉 Deciding when to use static vs instance members requires a deeper understanding in the logical design of your class and whether or not a given property or method is relevant to a given class instance or the class type (static). The class type exploses static members to help organize functionality that would not apply to 1.) any particular instance and 2.) can be used without any instances in memory.

+13

Part 3 of 5: Next, let's examine what the instance members have in common: 1. The instance properties reflect data specific to some loaded course. 2. The Save() method might convert the instance to a JSON string, then pass the string to the static version of this method described at the end of this review. The instance Save() method might look something like this: int Save() { string json = Json.Serialize(this); return Course.Save(json); } NOTE 1: I've chosen this approach with Save() to demonstrate how an instance method might use a static overloaded version of the same method name. NOTE 2: When Save() is invoked, it doesn't require a Course object as an argument to apply the save. The current instance itself will be saved. This very basic example reflects state and operations that apply specifically to the currently loaded instance of a Course object.

+13

Part 4 of 5: Before we start on the static members, know that the example of a static property used for tracking the number of courses loaded by the application is more for demo purposes than practical use. 😉 That said, when examining the static members, notice the static members for this Course class are not dependent on any given Course instance. The static property for LoadedCoursesCount will likely be incremented or decremented when each course is, respectively, loaded into or released from memory. Again, this is a horrible example I would never use in a real application. It's just to explain how static properties would not be tied to any specific instance.

+13

Part 5 of 5: Notice the overloaded static Load() methods receive a courseId or a JSON string to load and return an instance of a Course. While the static Load() methods work with a new Course instance, it does so as an object reference, rather than as a reference to itself. The last two static methods receive a JSON string that should be a valid serialized version of a Course instance. The static Save(...) method will likely use the static Validate(...) method to verify a Course instance can be loaded. If it is valid, then it will likely save it to a persistent storage like a DB, a queue, a file, or some API.

+13

HonFu This is such a great question. First, for clarification, the pseudo code I used isn't Java specific. It was meant to be general for most languages... keyword being "most". Python decided to shake things up a bit by introducing two versions of the static method compared to tradition uses in other languages. Both @classmethod and @staticmethod are tied to the class type, not class instances. The difference is @classmethod receives an implicit first parameter pointing to the single object instance of the class type - (known as the static instance in other languages). So, yes, as you mentioned, this behaves much closer to the traditional implementation of static in other languages. The cls parameter is essentially a reference to what other languages call the static instance. The @staticmethod is merely a stateless function in that it only has access to the args provided. It too is tied to the class type.

+12

~ swim ~ I wrote the answer to the way I learned the object-oriented design and presented it to myself, I would be grateful if you can correct me or confirm that I have learned correctly! You know very well, I do not think you're a beginner! Maybe, I'm not able to answer the question on the other way, except to explain first to myself and how I understood it!

+11

▪Class or static Members • A method or a field in a Java program can be declared 'static' . This means the member belongs to the class rather than to an individual object. • If a variable is static, then when any object in the class changes the value of the variable, that value changes for all objects in the class. For example: Suppose the Car class contained a speedLimit field that was set to 112 kmph (70 mph). This would be the same for all cars. If it changed (by act of Congress) for one car, it would have to change for all cars. This is a typical static field. Methods are often static is if they neither access nor modify any of the instance (non-static) fields of a class and they do not invoke any non-static methods in the class. This is common in calculation methods like a square root method that merely operate on their arguments and return a value. One way of thinking of it is that a method should be static if it neither uses nor needs to use 'this' .

+10

~ swim ~ In classic, procedural programming you try to make the real world problem you're attempting to solve fit a few, predetermined data types: integers, floats, Strings, and arrays perhaps. In object oriented programming you create a model for a real world system. A 'class' is a programmer defined type that serves as a blueprint for instances of the class. You can still have ints, floats, Strings, and arrays; but you can also have cars, motorcycles, people, buildings, clouds, dogs, angles, students, courses, bank accounts, and any other type that's important to your problem.

+9

~ swim ~ It sounds like you and I share the same opinions about Python. 👍 What makes it so confusing, in this case, is python implemented statics from C++, C#, and Java using a different name: @classmethod. Then, they introduced a new kind of stateless method bound to the class without access to the static instance and call it @staticmethod. In this case, python static is quite different from static in C++ / Java / C#. It's more like an unbound function using the class name as a namespace. It would have been better if they used the @staticmethod decorator where @classmethod is currently used. Then they could use a new decorator, @staticfunction, for the stateless unbound functions instead of @staticmethod. It was a really poor name choice to use @classmethod at all. It's confusing because a class method in any other language is used to describe an instance method. But python uses it for static methods. Hopefully this helps people understand the confusion and clears things up. 😜

+9

~ swim ~ Thanks for pointing out the duplicate post. It's odd... I posted, then edited and saved. The SoloLearn app must have posted my edit with a create request. Who knows. 🤷‍♂️ I think we now have a clear understanding of static methods for both C family languages and the outlier, python. 👌

+8

David Carroll, I (as a Python fan) get a bit confused, because in Python there are instance methods, static methods and class methods; and reading your explanations, Java's static methods sound to me more like Python's class methods. An example of my own, from my learning script: class StudyCard: @classmethod def set_today(cls, offset): cls._today = (int(time()) + offset*3600) // 86400 return cls._today This method is supposed to be used from outside StudyCard once before a learning session. _today gets initialized with the most recent time stamp once, and from then on, all StudyCards will refer to this class variable in order to decide if and when a topic will need to be repeated. Now static methods in Python to me look more like strangers of the class, that may have some relation, but are not really functionally tied to the class; they might refer to an instance, the class - or something completely different. Am I just confused or do the concepts really differ?

+8

Yes, I read your answer, David Carroll thank you very much, ➝ I'll read it again! 😊 I just want to know, do I learn and understand everything correctly? Because I do not have great experience with examples from the real world, and for me is everything revolves around the theory!

+8

~ swim ~ Classes are the single most important feature of Java. Everything in Java is either a class, a part of a class, or describes how a class behaves. All the action in Java programs takes place inside class blocks, almost everything of interest is either a class itself or belongs to a class. Methods are defined inside the classes they belong to. Even basic data primitives like integers often need to be incorporated into classes before you can do many useful things with them.

+8

voja 😄😅😅👍😉🍻 ➝ Angles == Uglovi ✌😁😃 In object-oriented programs data is represented by objects. Objects have two sections, fields (instance variables) and methods. Fields tell you what an object is. Methods tell you what an object does. These fields and methods are closely tied to the object's real world characteristics and behavior.

+8

Heres a simple way to understand it. int i static int j new Obj1 ➡ i++, j++ new Obj2 ➡ i++, j++ new Obj3 ➡ i++, j++ if we output obj fields i & j we get i=1 and j = 3 for each one. This is because j belongs to the class and i belongs to the object this is important to know when making animations because if all fields were static each time one object lets say hits a wall and changes direction this will affect all objects at the same time.

+7

Incase you want to make more then one object of class that its own methods, static methods belong to the class rather then the instance these class methods are accessible across all instances.

+7

• In Java everything is an object or a class (or a piece of one or a collection of several). • Objects send messages to each other by calling methods. • Instance methods belong to a particular object. • Static methods belong to a particular class.

+7

~ swim ~ To clarify, which python methods are you referring to? In Python, both @staticmethod and @classmethod decorators tie the method to the class. Or are you referring to both of these methods as static methods similar to C++ / Java / C#?