Java, from nothing · chapter 1 of 33
A class, an object, and main()
Chapter 1.1 · Part 1, Java from nothing · about 25 minutes
What you need before this chapter: nothing. This is the first chapter. If you have never written a line of Java, you are in the right place.
When you finish this chapter you will be able to:
- Write a Java file from scratch, compile it, and run it
- Explain the difference between a class and an object, and say which one exists at runtime
- Read the
public static void main(String[] args)line and say what every word in it does - Recognise the three errors you are most likely to hit, from the compiler message alone
1. The one idea in this chapter
A class is a description. An object is a thing that matches the description.
That is the whole idea, and it is worth being slow about, because every later chapter sits on top of it.
Think about a parking ticket. Somewhere there is a definition of what a parking ticket is: it has a number plate on it, and a time the car arrived. That definition is not itself a ticket. You cannot hand it to a driver. It is a description of the shape every real ticket will have.
Then a car arrives, and you print an actual ticket. Plate KA-01-4432, arrived at 9:15. That printed ticket is a real thing with real values in it. Another car arrives and you print a second ticket, with a different plate and a different time. Two real tickets, one description.
In Java, the description is a class and the real thing is an object. You write the class once. The program creates as many objects from it as it needs, each with its own values.
The word for "creating an object from a class" is instantiating, and an object is often called an instance. Those two words mean nothing more than what you just read, and interviewers use them constantly, so they are worth knowing from the first chapter.
2. Type this
Make a folder to work in. Inside it, create a file called exactly Ticket.java — capital T, and the extension .java. Java requires the file name to match the public class name inside it, so this is not a style choice; get it wrong and it will not compile.
Type this in. Do not copy and paste it. Typing it is slower, and that is the point: you will read every character, and you will hit the errors in section 5 yourself, which is how they stop being mysterious.