Java topic: objects

This is the first topic of my new java tutorial.

The first thing you need to know about the java language, is the difference between "objects" and "primatives".

Objects

Think of a programming object, as similar to an object in real life. It is something you can hold on to. It is something you can do things with, and sometimes do things to. It is also something you can pass around.

All java programs start with an object. Here is about the most basic object you can have in java.
Don't worry about fully understanding everything here: Just notice the general layout


class my_object {
	public static void main(String arguments[]){
	}
}
This is the smallest standalone java program you can have. Every java program requires at least two things:
  1. An object definition, via a "class" definition. The definition will be within an outer set of curly braces { }
  2. A "main" method, which has its own set of { }

If you put the above in a file named "my_object.java", you could compile it with
"javac my_object.java", and you would get a program that you can run! .... it just won't do anything.

If you do choose to try it out, make sure that you get all the punctuation exactly as shown, otherwise it will not compile correctly.

The spaces on the left of lines don't matter for compiling, but it helps later on for style. If you chose to write it all on one line, or two, it would work just the same.

Objects that do something

Having a program that does nothing, isnt very useful though! So let's make it do something. The "main" part there, is called a "method". Each object may have some number of methods for doing things.

Lets make our object print something on the screen:

class my_object {
	public static void main(String arguments[]){
		System.out.println("Objects can show off!");
	}
}
// If you wanted to actually see this work, you would need to either run it
// from commandline, with "java my_object", or have a good IDE that shows output.
// Again, make sure to copy all punctuation, including the semicolon!
In java, you normally refer to the methods contained in an object, by joining the object, and the method, together with a dot. If we were to refer to the main method in absolute terms, we would say that it was "my_object.main()".
In the same way, you can refer to objects contained inside another object.

To understand the above example more fully, it helps to know that "System" is a special, standard object, with some very useful methods and objects contained within it. In the above example, the System object, contains another object, called "out", which is short for "output". In the above case, "println", is a method of the "out" object, that "prints a line" to the program's output area.

Hint: You can tell something is a method, because it has ( ) on the right of it. There may, or may not, need to be something inside of the parenthesis.

Next Lesson: Primative types