To define a class in Java use the keywords (words that Java already understands) public class
followed by a ClassName. Then the body of the class is enclosed in a starting {
and ending }
as shown below.
public class ClassName
{
}
In Java, every open curly brace {
must have a matched close curly brace }
. These are used to start and end class definitions and method definitions.
A class in Java can have :
– fields (data or properties)
– constructors (ways to initialize the fields)
– methods (behaviors)
– a main method for testing the class.
It does not have to have any of these items. The following would compile, but what do you think would happen after you instantiate it?
public class FirstClass
{
}
The class FirstClass
doesn’t have anything inside of it, so the computer wouldn’t know what to do if we asked to instantiate an object of the class.
When you ask Java to run a class it will start execution in the main
method. The main
method starts with public static void main(String[] args)
in the following class. As you have seen in previous examples, if you want to run code in java, it must be in a main method.
public class SecondClass
{
public static void main(String[] args)
{
System.out.println("Hi there!");
}
}
The code above will just print “Hi there!”. In Python you would have used the print command. In Java, that same command is a bit longer, System.out.println
. In the case above we are just printing the characters between the first "
and the second "
. The "Hi there!"
is called a string literal. A string literal is zero to many characters enclosed in starting and ending double quotes in Java.