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.

Java Basics: Classes, Objects, Fields, Methods, and the Keyword Static

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:

Cat.java
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 + ".";
  }
}
CatsTheMusical.java
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;
  }
}

If you understand this code, particularly how the keywords this and static work, and you can predict the output as shown below,
Cat Code Output

then you probably don't need to expand the section below and can continue.
Cat Code Explained

Now you are ready for some more advanced Java!

Types, Primitives, and Generics

TODO... but until then

Inheritance, Abstract Classes, Interfaces, and Inner Classes

TODO... but for now

Data Structures

TODO... but for now

  • No labels