Question on java (the programming language)

Teaching myself java after having programmed in pascal and ANSI-C. I’m starting to play around with writing methods and I wrote this:

Of course got the infamous “non-static method cannot be be referenced from a static context.” After trying to understand the error, I changed the second line to:

  1. What exactly does that error mean?
  2. How did making summate static solve the problem?
  3. Is there a better way to do this?
  1. Static methods/variables are members of the class, while instance methods/variables are members of an instance of the class. Since you aren’t creating an instance of “firstmethod”, you can’t call any method on that instance.

  2. Making the method static means you can call the method without instantiating the class first.

  3. Create an instance of firstmethod with a constructor as shown: firstmethod m = new firstmethod();

  4. Incidentally, it’s standard Java naming to always name a class starting with a capital letter, always name a variable starting with a lowercase letter, and use camelCase everywhere except constants. I can’t tell you how unconfortable it was for me to not capitalize the name of your class :slight_smile:

You have to understand what “static” means. A class is a collection of variables/properties and methods/functions. It is an abstract thing - a “concept” if you will. In order to use the class, you have to “instantiate” it - that is, create an instance of the class, make a “physical” model of the class rather than abstract. After you do that, you can reference the variables and call the methods of the class. When the class is not instantiated, there’s nothing to call - those properties and methods exist only as abstract “concepts”. It’s like blueprints vs. a building - the door may exist in the blueprint as a concept, but it does not exist until you “instantiate” the blueprint as a building and you cannot open the door in the blueprint - only in the building.

Except for “static” properties or methods. Those exist independently of the instances of the class and apply to the whole class rather than to the instances. For example, you may have blueprints (“class”) and buildings built from the blueprints (“instances”). But if you want to know the total number of buildings ever built from the blueprints, you may have a static property called “TotalBuildings” that is static - it exists in the class, not in any particular instance. The property can be referred to from any instance of the class, or from outside the class, it is the same for all those calls. Static properties or methods do not need any instance of the class to exist in order to be called, they are called by referring to the class, not to the instance.

Now we get to the error. Since static functions exist in the class, but not in any particular instance, they cannot reference any instance properties or methods - since those only exist when instances exist, and the static function may be called before any instance exists.

Static methods are methods defined on the class – there is no instance of the class associated with this method. Non-static methods are associated with instances of the class – there is required to be an instance of the class for a call to one of those methods to make sense.

Non-static methods can call both static and non-static methods. If calling a non-static method, the associated instance is the same as the instance associated with this method. But static methods can only call other static methods because there is no instance already associated with them.

Out of necessity main() is always a static method. At the start of the program, no classes have been instantiated, so only a static method could be called. But an alternate way to correct your program would be to have main() instantiate your class before calling the method, like:



public static void main (String[] args) {
int first = 1;
int second = 3;
int third = 9;
firstmethod x = new firstmethod();
int answer = x.summate (first, second, third);
System.out.println ("The answer is " + answer + ".");
}


That way summate is being called on a specific instance (i.e. x) of the class, rather than in a static context.

If you are not entirely comfortable with Object-Oriented programming, you should try to become more comfortable with it in order to use the language, since in Java OO is obligatory.

I think I got Terr’s analogy but let me just check my understanding.

I want to make a method turndoorknob. As long as it is not instanced viz just blueprints with no real door and I try to call turndoorknob, the compiler says “You can’t because you can’t turn the theoretical (blueprint) doorknob. You need a real doorknob to turn so make a door first.”

So now I write
Door frenchdoor = new Door();
and now java will let me call frenchdoor.turndoorknob since there’s actually a door/knob to turn.

Please say I got it because using that analogy to see if I understood, I made my first object complete with methods that can be called from another class. And it WORKS!

100% correct.

Might also be worth noting that it’s probably not a great idea to use “method” as part of the name of a class.

The responses above are right. Maybe I can offer a bit of additional explanation:

If a class MyClass contains a non-static variable myVar (also known as a field or property), then each instance of a MyClass contains its own instance of the myVar variable. (In other, more rational universes, this would be called an instance variable. It seems quirky to me, to use the word “static” to define a class variable or method. Seems like a word borrowed from C and given a different meaning.)

Now, let:
MyClass period1 = new MyClass() ;
MyClass period2 = new MyClass() ;

Now, call a method within the class, using each of these two instance objects:

int totalCredits = period1.hours() + period2.hours() ;

The method hours() might (and typically would) contain references to instance variables within the class. The two calls to hours() above would each refer to its own instance’s instance of myVar. So how does the code in hours() know which instance is this in each call?

Because, the target object is passed to the method as a (poorly kept secret) parameter. In the call period1.hours(), the object period1 is one of the parameters parameters passed to the function (even it isn’t called a parameter in OO terminology). In a non-OO language, the (near)-equivalent call would be:

int totalCredits = hours(period1) + hours(period2) ;

Now to the point: Instance (non-static) methods, by definition, are intended to be used in this way: To include references to instance variables in each particular this object when they are called. Thus, there absolutely must be a this when the method is called.

The example in the OP might be confusing because it’s a degenerate case: The body of the function does not refer to any instance variable of the class. Therefore, it hypothetically could be called with:

int answer = summate (first, second, third);

Except that it’s defined as an instance (non-static) method. Thus, even though it doesn’t refer to any instance variables, it could. Thus, it must be called with a this object, as in:

int answer = myThisObject.summate (first, second, third);

so that any references to instance variables will have, you know, an instance to work with.

Thus, if a method is intended to not refer to variables of any particular instance, but instead is intended to be used as in the OP example, then the method must be declared as a static (i.e., class) method rather than an instance method.

Use [noparse]




[/noparse] instead of [noparse]

[/noparse] for code blocks to preserve the indentation. It makes your code much easier for us to read.

Just as an aside, after looking at the languages you originally used to learn programming, it might help you to pick up a book (or scrounge the Internet for articles) about the basics of Object Oriented Programming (or OOP for short).

You would probably understand Java better if you picked up the basic reasons why OOP was invented in the first place, because Java strives with some success to be a model OOP language. It will also help you if you ever decide to pick up C++, C#, or any one of the other gazillion OOP languages out there.

I agree 100% with Bremidon. I started life as a Fortran and Cobol programmer and picked up C easily enough, but didn’t see what C++ was trying to achieve. After my company sent me on an OOP design course it all made sense and picking up Java and C# was easy. I still don’t like C++, I think it’s ugly.

I was considering buying this book but I was hesitant to buy it blind. Does anyone have an opinion on it?