Below is a short tutorial designed for someone who is familiar with programming (potentially only at the level of MATLAB), and has never learned or long forgotten Java. After explaining the very basics of classes and objects, we skip all of the syntax and control flow and go straight to what you will need to complete the workshop. If your Java is not strong, please take the time to understand this tutorial, otherwise you will most likely be lost during the workshop. It should take about 30 minutes.
What are classes and objects?
In Java, all code is associated with a class. Classes have fields and methods. Instances of classes are created with Constructors and called Objects. Once an Object has been constructed, its methods can be called and its fields can be accessed. Here is a concrete example with two simple classes:
public class Cat { private int age; private String name; private Cat friend; public Cat(String name, int age) { this.name = name; this.age = age; friend = null; } public String getName() { return name; } public Cat getFriend() { return friend; } public void setFriend(Cat friend) { this.friend = friend; } public String sayHello(String aboutMe) { return "Hello World! My name is " + name + " and I am " + age + " years old." + " I am " + aboutMe + "."; } }
public class CatsTheMusical { public static void main(String[] args) { Cat mist = new Cat("Mr. Mistoffelees", 8); System.out.println(mist.sayHello("magical")); Cat garf = new Cat("Garfield", 12); System.out.println(garf.sayHello("tired/hungry")); mist.setFriend(garf); System.out.println(mist.getName() + " and " + garf.getName() + " are friends? " + CatsTheMusical.areFriends(mist, garf)); garf.setFriend(mist); System.out.println(mist.getName() + " and " + garf.getName() + " are friends? " + CatsTheMusical.areFriends(mist, garf)); } public static boolean areFriends(Cat cat1, Cat cat2) { if (cat1.getFriend() != null && cat2.getFriend() != null) { return cat1.getFriend() == cat2 && cat2.getFriend() == cat1; } return false; } }
Lets make sure we understand how this works. First, lets talk about the contents of the files Cat.java
.
- Fields: The class
Cat
has three fields,name
,age
andfriend
. Each field has a type, which ensures that we can only store aString
inname
, anint
inage
and anotherCat
infriend
. The wordprivate
before each field indicates that the field can only be accessed from within the classCat
. - Constructors: The class
Cat
has one constructorpublic Cat(String name, int age){...
}. In the constructor, the fieldsname
andage
are initialized with the values given in the arguments, whilefriend
is simply set tonull
. Because the constructor is public, it can be invoked from other classes. An example of the invoking the constructor can be seen inCatsTheMusical.java
. - Methods: The class
Cat
has four methods,getName(){...
},getFriend(){...
},setFriend(...){...
} andsayHello(...){..
}. The keyword{{public}} indicates that the methods can be called outside of the classCat
. The second word in each method is the return type, or the type of the result of the method. Notice thatsetFriend(...)
has a return type ofvoid
, indicating that nothing is returned. The first two methods are examples of getter methods, as they simply retrieve the value of a private field. The third method is a setter method, which allows the fieldfriend
to be changed from outside the classCat
.
Now lets talk about the other file CatsTheMusical.java
.
- Static Methods: Methods that are
static
, while associated with the class they are written in, are not associated with any particular instance. They can be invoked by using{{[class-name].[method]}}. For example, see the invocation ofareFriends(...)
withinUnknown macro: {main(...)}. - main(...): All Java program must start with the code
public static void main(String[] args){...
}. From here, we will follow the methods and constructors into other class files. The arguments,String[] args
can be accessed by callingargs[0]
etc. and can be set by going to the top menu bar and then selecting Run → Run Configurations..., then selecting the Arguments tab in the center and filling out the Program Arguments box.
Now that we have the basic terminology down, lets examine some of the finer points which may be confusing to non-Java programmers:
- Given an instance of a class (e.g. for
Cat c = new Cat(...)
,c
is an instance), non-static methods from the class can be called by [instance name].[method name] (e.g.c.getName()
). Similarly, non-static fields can be accessed by calling [instance name].[field name], (e.g.c.name
). However, methods or fields labeledprivate
can only be called/accessed from code written within their own class file. - Within a constructor, we can directly access the fields of a class by name without reference to any particular instance, as it is implied that the instance is the one that is being built. For example, in the
Cat
constructor, we make the assignmentfriend = null
. However, when there are argument variables with the same name as the field variables, they take precedence and shadow the fields variables. To reference the fields once they have been shadowed, you need to use the keywordthis
. In fact, you can use the keywordthis
whenever you want to refer to a field or method of the instance of the class being built by the constructor, regardless of whether there is shadowing. Analogous rules apply for fields and methods inside other non-static methods. - In static methods, we cannot refer to any non-static fields or non static methods of the class without also providing an instance, as static methods are not associated with any instance. Similarly, the keyword this cannot be applied.