+ 3

Is there a rule for methods?

Like should I create them in a different class and call them in the main thing that gets executed automatically in another class? Or just make them inside the same class and make them static to be able to call them? It's just preference or it depends?

17th Jul 2021, 3:09 PM
Jace🎭
Jace🎭 - avatar
5 Réponses
+ 11
In object-oriented programming, we talk about stuff in terms of objects and methods (i.e, what actions an object can perform). Objects are instances of classes. For example, Human is a class, while John, an object, is an instance of a Human. Whatever non-static method you place under the Human class should reflect something a normal human should be capable of, e.g. eat, drink, walk, talk, etc. As such, John can do stuff like John.eat("pizza") John.drink("pepsi") Now, let's say that you want John to go to space. You can achieve this in multiple ways. You can create a new method under the Human class to allow John to John.goToSpace(). Or, you can create a new SpaceCraft class, and put the goToSpace method under that class. spacecraft1.goToSpace(John) // SpaceCraft instance brings John to space. Which is better? Are all humans capable of going to space? If the answer is no, then the latter implementation may better reflect how stuff works IRL.
17th Jul 2021, 3:51 PM
Hatsy Rei
Hatsy Rei - avatar
+ 5
being Java an object language, which coexists also with static environments, the first thing to do in the main would be to instantiate an object, even of the class to which the main belongs to start that series of method invocations and creation of objects that they carry out the program. if you use java in a static environment, maybe you have the wrong language. however it is always possible to distort the use of a language. think of objects, and methods disappear. they become messages accepted by the objects. if you keep thinking about the data and the methods separately, you will keep asking questions like that after all, the paradigm of object-oriented programming is "Determine which classes you want; provide a complete set of the operations of each class; make explicit what they have in common through inheritance." but if you talk about methods before classes, you don't need an object language
17th Jul 2021, 4:00 PM
Ciro Pellegrino
Ciro Pellegrino - avatar
+ 3
there are no rules but there are standards. it depends.
17th Jul 2021, 3:16 PM
Bhavik Mahalle
Bhavik Mahalle - avatar
0
Could you elaborate, how it's seen to choose one way over other, maybe there's one that's considered best practice?
17th Jul 2021, 3:28 PM
Jace🎭
Jace🎭 - avatar
0
static method can't use non-static fields (if that has to keep value between two calls of the method). class Counter { private int value=0; static int increment() { return ++value ; //error } }
17th Jul 2021, 3:41 PM
zemiak