Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

What is the difference between a "Method" and a "Class"?

Hello all,

I've been wondering what's the difference between a method and a class.

I was doing a test and it asked me to create a class called BlogPost. My answer was:

public BlogPost {
}

I ended up getting the answer right.

Later on in the test, they identified a method called "main", which was typed out like this:

public static void main() {
}

From my experience with Java (which isn't much lol), "static" and "void" aren't required so the code can be typed out like this:

public main() {
}

So here's my question. What is the difference between a method and a class in terms of typing them out? The only difference I found is that methods have parenthesis whereas classes doesn't have anything.

Is that really the only difference between the two in terms of writing the code? A pair of parenthesis to pass through parameters?

2 Answers

I will start this response with 'In my understanding' and go from there... happy to be corrected. :)

Question 1. Difference between a Method and a Class.

They are quite different from each other. I think of a class as a construct, it has properties, initialisers and contains methods. A class is not called directly as you would a Method, but you would call Methods inside classes. In a game you may define a class of 'Monster'. This class would have properties like 'health', 'weapon', 'armour' etc, and may contain Methods like 'ReceiveDamage', 'DeathSequence' etc.

A method is initialised inside a class to do a sequence of events (possibly receiving values itself), like 'ReceiveDamage' might reduce health by a received value of damage. It may play 'hit' noise, check health is greater than 0 and if not then execute 'DeathSequence'. Another interesting definition is that outside of a Class, Methods are called Functions (I believe;).

Question 2. Coding difference.

Class

public class Monster {
  public int health;
  public string weapon;

  public Monster(int startHealth) {
    health = startHealth;
  }
}

Method

public ReceiveDamage(int damage) {
}
A class is a set of rules you write that govern an object. 

An object is what a class defines.

A method is a bit of code that can be called 

in JavaScript, which I know Java isn't...methods do things.  
JavaScript doesn't have class in the same way Java does
so I have nothing to add about that