2

Why can't we just make all methods and variables static, to save ourselves from the hassle of making objects?

I have actually had this question ever since I started learning Java a long time ago, but never asked it. I know that if a method or variable is not static, you can call it using an object you create:

public class classwithmethodandvariable {

    int i = 7;

    public void hello() {
    }

}

You can call this like so:

public class myMainClass {

    classwithmethodandvariable obj = new classwithmethodandvariable();
    classwithmethodandvariable.i++;  // ACCESS INT I AND INCREMENT
    classwithmethodandvariable.hello();  // CALLS METHOD HELLO

}

But, if we had made the method hello() and variable i we could have done everything with less lines of code, right?

public class classwithmethodandvariable {

    static int i = 7;

    public static void hello() {
    } 

}

You can call this like so:

public class myMainClass {

    classwithmethodandvariable.i++;  // ACCESS INT I AND INCREMENT
    classwithmethodandvariable.hello();  // CALLS METHOD HELLO

}

Why don't we do that? I have seen another question like this, but the answer says “Because you can't access instance variables from static methods”. But then what if you make the variables also static?

Community
  • 1
  • 1
Ruchir Baronia
  • 7,406
  • 5
  • 48
  • 83
  • 3
    because of this thing called OOP – Sleiman Jneidi Jan 03 '16 at 00:21
  • 1
    Actually, why have classes _at all_? Why not just dump everything inside `main` and be done with it? – Tunaki Jan 03 '16 at 00:22
  • 4
    Because when something is `static` there is just one. What if you want to model a car? What if you want to model two cars? Again, if you can do it with just *one* then `static` may be fine. – Elliott Frisch Jan 03 '16 at 00:22
  • 4
    This is basically asking, "why do we bother with objects in an object-oriented language?" Hence, you may wish to spend some time learning [more about object-oriented programming](https://en.wikipedia.org/wiki/Object-oriented_programming) and its pros and cons. – CommonsWare Jan 03 '16 at 00:22
  • @ElliottFrisch thats easy, u create another class called car1,car2 and when you run out, you write a script to generate classes :) – Sleiman Jneidi Jan 03 '16 at 00:26
  • 3
    @SleimanJneidi I hear VW is looking for software developers! – Elliott Frisch Jan 03 '16 at 00:30
  • @ElliottFrisch SO is full of them :) – Sleiman Jneidi Jan 03 '16 at 00:32
  • @CommonsWare Thanks for your response. I have actually spent lots of time researching `static`, and I know what an object does. To me though, it seems there are much more pros in the side of `static` than actual objects. Although this may seem like a silly question, asking about the very principals of what I've been doing for a very long time, I feel many other people may also be slightly unsure of why to even use objects if there is a better way. Feel free to write an answer, to help me, and the others that are also slightly confused! :) – Ruchir Baronia Jan 03 '16 at 00:36
  • @SleimanJneidi Thanks for your response. It seems there are much more pros in the side of static than actual objects. Although this may seem like a stupid question, asking about the very principals of what I've been doing for a very long time, but I would really appreciate an answer. Feel free to write an answer, to help me, and the others that are also slightly confused! Why isn't it called SOP (Static oriented programming)? – Ruchir Baronia Jan 03 '16 at 00:38
  • @Tunaki Well, [thats](http://programmers.stackexchange.com/questions/154228/why-is-it-good-to-split-a-program-into-multiple-classes) different, because of organization. Although this may seem like a stupid question, asking about the very principals of what I've been doing for a very long time, but I would really appreciate an answer. Feel free to write an answer, to help me, and the others that are also slightly confused! Why isn't it called SOP (Static oriented programming)? Thanks for your response! – Ruchir Baronia Jan 03 '16 at 00:41
  • I would suggest reading a relevant discussion on the [Programmers StackExchange](http://programmers.stackexchange.com/questions/98083/cant-i-just-use-all-static-methods) – Ed Holloway-George Jan 03 '16 at 00:48
  • @RuchirBaronia imagine what the String class would be like if all its data and methods were static. For a start, every string would have the same value. – Klitos Kyriacou Jan 03 '16 at 00:55
  • @KlitosKyriacou Why would every string have the same value? Feel free to post an answer also. Thanks so much! Let me know :) – Ruchir Baronia Jan 03 '16 at 01:02
  • @RuchirBaronia that's the meaning of `static`: a single value for the whole class. If you want each string to have its own value, then you have to make its data be instance variables. – Klitos Kyriacou Jan 03 '16 at 01:04
  • @KlitosKyriacou But we are making _different_ static variables, right? Please let me know :) – Ruchir Baronia Jan 03 '16 at 01:08
  • @RuchirBaronia What would such an implementation look like? When you wanted to, for example, assign a string a new value, would there be some function that would pass precisely the right combination of status variables for that particular string to? How would a function (like concatenation) return a string? How would you make a collection of strings? – David Schwartz Jan 03 '16 at 01:14
  • @RuchirBaronia The idea is that in a program, we want to have many things that follow the same pattern - people all have a name, an age, a height, etc... - The class represents that pattern (name, age, height), and the object is the individual person (Bob, 25, 180cm). Now, you could make lots of static classes for each person, but that's a lot of repeating yourself, and it doesn't let you deal with an unknown number of people (and people you only know exist at runtime). – Gareth Latty Jan 03 '16 at 01:14
  • @Latty I'm not talking about static classes though, I'm just asking if we can have a regular class, with all the variables and methods in it static. – Ruchir Baronia Jan 03 '16 at 01:17
  • @RuchirBaronia Static variables and methods exist on the class itself, not on the instance - the value is shared across all instances - that would mean you could have many objects, but they would all be Bob. – Gareth Latty Jan 03 '16 at 01:18
  • @Latty So I cant define two static variables in one class? `public class example{ static int i; static int i2 }` I'm sorry, but why can't I just have two variables? Thanks Latty! – Ruchir Baronia Jan 03 '16 at 01:22
  • @RuchirBaronia You can, but what if I'm creating a system where anyone can sign up? I need a potentially unlimited number of people. If I have to have a variable for each person, I'd need to write an infinite number of variables. Not to mention that then I'd have to write the code to work with those variables for each one, rather than writing it against the interface of the class, and passing in different objects. – Gareth Latty Jan 03 '16 at 01:23
  • 2
    Static and non-static properties have their own ups and downs. Apples and oranges. You can't really say that static properties are better or worse than non-static ones. It'll depend on your scenario, and most likely you will need **both** for pretty much any program. – Saturn Jan 03 '16 at 01:25
  • @Latty Okay, so I'm starting to understand (10%). But wouldn't you need to do the same in signing up for objects? Everytime they click `Sign up!` you would need to make a new object right? I think i'm confusing myself even more... – Ruchir Baronia Jan 03 '16 at 01:25
  • @Voldemort Do you mind providing some of those examples (maybe by posting an answer) so that I can better understand? Thanks "he who shall not be named!" – Ruchir Baronia Jan 03 '16 at 01:26
  • @RuchirBaronia You create an object, but then you can store those objects together (say in a list) and treat them the same. Then you can do the same things to each of those objects. This means you don't need to know how many times you need each thing, and don't need to write different code for each time. – Gareth Latty Jan 03 '16 at 01:27
  • @Latty Okay, this makes sense, but I'm having a hard time understanding how you would actually code that. Do you mind providing me some sample code of what you just said. Maybe post an answer also? Thanks so much Latty! – Ruchir Baronia Jan 03 '16 at 01:28
  • @RuchirBaronia Take a look at this: https://docs.oracle.com/javase/tutorial/java/javaOO/examples/Person.java - Now, in this example, the objects are created in code, but it shouldn't be hard to imagine instead that there is some user input that makes them in a loop. – Gareth Latty Jan 03 '16 at 01:30
  • @Latty I dont see any methods getting called here except for `createRoster` and `Person`. Actually, I dont even see `createRoster` being called...Is there some sort of main function that goes with this code? – Ruchir Baronia Jan 03 '16 at 01:41
  • @RuchirBaronia It's just an example, imagine something calling `createRoster()` and using the list of people. Better yet - try it. – Gareth Latty Jan 03 '16 at 01:42
  • It's all about reduction of connections and complexity which are the big bugaboos when trying to create large programs that work, and that debug, that can scale even larger. – Hovercraft Full Of Eels Jan 03 '16 at 01:48
  • As this question has been put on hold - I have tried to show a very basic example of some of the flaws of using classes like this in this [Gist](https://gist.github.com/ed-george/5a77abd09694b6d8e569) - The OOP principles should be a little clearer from this I hope – Ed Holloway-George Jan 03 '16 at 01:52
  • @EdGeorge That is great help, and I have read through it all. I have a question though, won't boolean toggled get permanantly changed though, making the toggle for the next object impossible? PS: I have voted to reopen the question, so that you can post as an answer! – Ruchir Baronia Jan 03 '16 at 02:17
  • You'll need to be more specific, which classes are you referring too? Also, why not download the files and try for yourself. It is the easiest way to answer these questions – Ed Holloway-George Jan 03 '16 at 02:18
  • @EdGeorge I tried it and figured it out. Now, in this case using the static doesn't work, but what if we just called method `toggled()` in class main for the static option after we changed the boolean doing `StaticLavaLamp.toggled = false;` that would be doing the same thing then? – Ruchir Baronia Jan 03 '16 at 02:40
  • @HovercraftFullOfEels I would love to see an example of that complexity in action. I have voted to reopen. :) – Ruchir Baronia Jan 03 '16 at 02:42
  • @Latty Thanks, thats a good example, and I think I am understanding it better! If you want you can post that answer, to help others who come across this question. I have voted to reopen. :) – Ruchir Baronia Jan 03 '16 at 02:44
  • @ElliottFrisch comment is the answer. Very simple, straight forward – paul Jul 31 '20 at 08:44

3 Answers3

6

Object oriented programming is designed to hide state in an object and then provide a method (aka behavior) that modifies the state.

This is a very simple idea, but when combined with inheritance, interfaces, and other common design patterns allows for a very maintainable system.

The use of only static methods would prevent many of these design patterns from working, and so you would sacrifice maintainability, and extensibility of your system.

crypto
  • 83
  • 7
2

Why can't we just make all methods and variables static, to save ourselves from the hassle of making objects?

You can. If you really wanted to, there is nothing stopping you1, 2.

However, that is not how Java was designed to be used. And you will find that your code base get increasingly hard to test and maintain as it gets larger (compared to OO code). And you will also find that other Java developers are liable to run away screaming if they are asked to read your code.

If you really cannot get your head around OO, and/or you cannot accept that OO's benefits out-weigh the "hassle of making objects", then you would be better off using another language. Pick one that is non-OO (like C, old-school BASIC) or that is more conducive to non-OO programming (C++ used like C, Python, Perl, etc.)


1 - "Besides, a determined Real Programmer can write FORTRAN in any language." is one of the best lines in "Real Programmers don't use Pascal."

2 - Actually, some Java APIs can only be used effectively if you create and use custom classes.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 2
    Surely, there are *hundreds* of articles on the web that explain the benefits of OO programming ... with examples. – Stephen C Jan 03 '16 at 01:26
  • 1
    Probably the Google (Guava) and Spring guys "would be better off using another language" as their codebases are littered with public statics/singletons...the more I look at large open source Java projects used by the majority of Java developers the more I see non-OO code – Zack Macomber Jan 11 '19 at 15:14
1

Think of a cookie (the kind you bake) as an object. Now think of a cookie cutter as a class. Just as the cookie cutter is used to makes cookies, classes are used to make objects (via instantiation, typically by an operator named new). An object is an "instance of a class." Objects are NOT classes. Don't confuse the two. Objects are instances of classes. Buildings are instances of blue prints, cookies are instances of cookie cutters. A class is a set of "instructions" for making objects. You can add your own information to a class by using statics. Just like the instructions for making objects, there is only one of every static in a class. If you only need one instance of a class, you can make all the variables static (this works, but it's not advised -- there are better ways). If you need multiple instances of a class, like a collection of identical objects (a basket of kittens) or related objects (a basket of mammals, which includes kittens and puppies), then, in general, you don't want to define variables as static (for example, each animal has its own birth date, name, description, weight, etc.). Anything you define as static exists only once and is common to all of the instantiated classes. If any one instance of the class changes the static value, all instances of the class see that change.

I suggest you read a good book about object oriented programming. Here's a good one:

Object Oriented Modeling and Design by James Rumbaugh, Michael Blaha, William Premerlani, Frecerick Eddy and William Lorensen).

mbmast
  • 960
  • 11
  • 25
  • 1
    The class is the dough and the cookie cutter makes the objects. The dough is friendship bread because it keeps regenerating and you can make as many objects as you need. – nicomp Jan 03 '16 at 00:57