Monday, April 15, 2013

Introduction to Java: Definitions

Another thing I struggled with when learning Java was what the difference was between a Class, an Object, and a Method.  Through personal experience and web searches, I have come up with this explanation:

A class is the basic building block in Java.  It consists of variables and methods.  Here's an example:

public class Cat {  //this is the class

//these are the variables in the Cat class
String name;
int age;
int weight;
String color;

//these are the methods in the Cat class
public void eat() {
}

public void sleep() {
}

public void meow() {
}

}

A variable is a little bit of memory that stores a value to be used in a program.  A String is a bit of text, like "Hello!" or "rainbow".  In the Cat class, the String variables we have are name (the name of the cat), and color (the color of the cat).  An int is an integer, like 7 or 13.  In the Cat class, the int variables we have are age (the age of the cat) and weight (the weight of the cat).

An Object is an instance of a class.  If we want our program to create and use a cat, we need to create a Cat object:

public void main() {  //this is the main method of our program

//this is where we create the new Cat Object
Cat Fluffy = new Cat;  //Fluffy is the variable name given to the Cat Object

}

method is a task or group of tasks.  If you are familiar with mathematical functions, you might want to think of a method as a function.  In the Cat class, the methods are eat(), sleep(), and meow().  The parentheses after the method name indicate what kind of parameter will be passed into the method.  In this case, eat(), sleep(), and meow() do not require a parameter.  In the next blog post I will give some examples of methods with parameters and how they work.



No comments:

Post a Comment