JoC #3: Classes and objects

    If a man writes a book, let him set down only what he knows.
    I have guesses enough of my own.

          — Goethe

Alright, now it finally starts getting interesting! After the previous talk about installation, now we’re getting started actually doing stuff.

Watch this episode to get the first feel for working with Greenfoot, and see what classes and objects are all about.

Download video

Concepts discussed: class, object, method, instance, return value, return type, void, int, boolean

And, as I said in the video: Follow @JoyOfCode on Twitter to get updates when new episodes are posted.

Scenario download for this episode: hedgehogs.zip      (save and unzip before opening)

The Joy of Code, #2: Installing Greenfoot

     A professor is someone who talks in other people’s sleep.
          — attributed to W.H.Auden

Straight on the heels of the first episode comes the second: Installing Greenfoot.

We’re still not quite ready to write code, but we’re getting there. Setting up the environment is important, so we’ll do that first.

Download video

I made one mistake in the video: For running on Mac OS, Mac OS X 10.5 (Leopard) is required as a minimum OS version (not Tiger, as I said in the video).

The links mentioned in the video are:

The Joy of Code, #1: Introduction

    Everything that is worth doing is worth doing well.  
        — proverb 

Here is the first instalment of the Joy of Code programming tutorial. No coding yet — this intro just shows you what you’re getting into if you choose to follow this tutorial.

Download video

If you are itching to get your hands dirty and start coding: great! That’s the kind of reader I like. Don’t worry, we’ll get there very soon.

Links mentioned in the video:

Greenfoot scenarios shown in video:

(Note: At this stage you are not expected to do anything with these scenarios yet. These are just here for those of you curious to play without waiting for me to introduce things.)

Download video

The Joy Of Code: Join us for a free online programming course with Java and Greenfoot

Want to find out how to write a computer game? Interested in learning programming? Curious about object-oriented programming and Java? Heard about Greenfoot, but don’t really know what it is? Teaching programming to others?

If any of these is you — read on!

We will soon start here, in this blog, a programming course. It will be done mostly in video format (often screencasts of actual programming sessions). We will start at the very beginning — assuming you know nothing about programming at all — and then progress through a sequence of many important topics. We will, assuming things go well, eventually arrive at quite sophisticated concepts and hopefully write some really cool programs along the way.

There will be two “streams” to this course: The main stream, aimed at novice (or intermediate) programmers, and — occasionally weaved in — an “educators’ stream” with commentary for teachers. The teacher commentary will talk about how to teach programming (rather than learning it).

So, I hope to hit three possible audiences with this:

  • Folk who want to learn about programming. Maybe you don’t know any programming at all, or you know some already but want to learn more.
  • People who know about programming, but want to learn about Greenfoot.
  • Teachers of introductory programming classes who want to see and discuss ideas about teaching programming.

For this blog, we will use Java and Greenfoot. If you dont know what that is — don’t worry. The first couple of posts will show you.

Above, I said “we” will soon start. It’s “we” because I hope I won’t be alone here. I would like as many of you as possible to get involved. The course has not been developed yet, and I will make it up as I go along. While I do that, I’d like you (yes: you!) to give me feedback in comments. Ask questions, tell me what’s unclear, tell me what I should explain again or in more detail, tell me what else you’d like me to talk about.

If things go well, this can become interactive, and paced and guided by viewers — that’s you.

I hope that over the first few weeks I’ll manage to get a handful of readers/viewers who join in and help me move this along.

The course will start in a few days. So: Bookmark this page, subscribe to the RSS feed, tie a knot in your handkerchief, set a calendar reminder, or whatever it is that will remind you, and come back soon!

 

Copyright, license and redistribution

It’s necessary to add some license info here – these questions always come up eventually. So: I will publish these videos here on my blog and on Youtube. Additionally, I will make the videos available for download.

All videos are Copyright © Michael Kölling.

You are explicitly permitted to download, use, show and distribute these videos for the following purposes:

  • For any personal use.
  • For the purpose of teaching a class of students, where you are the instructor.

You are not permitted the following (unless with explicit written permission):

  • Re-publication to the general public, via websites or on other media (CDs, etc.).
  • Redistribution for profit.

That is: You cannot do two things: Sell my videos for money, and duplicate them on your own web site.

The reason for the second is that I’d like people to come to one place here, because I hope to have some discussion with viewers on the site here in the comments. I do not want to split up out viewer community.

BlueJ downloads hit 10 million!

The total downloads of BlueJ hit 10 million today. We started recording download numbers in 2001. Early on, downloads ran in the low hundreds per month, and we were really excited when they reached first 10,000 in a year, and later topped 100,000.

Currently, BlueJ downloads run at 2.5 million per year, and are still rising. Hitting the total of 10 million was a nice milestone.

 

Java 7 for introductory programming — does it make a difference?

The recently released BlueJ 3.0.5 brought full support for Java 7. While it is always good to be up-to-date with the latest versions — what does that actually mean for introductory programming teaching?

Java 7 brought a considerable list of new features to the Java system. Most of them deal with fairly advanced or specialised topics, and will have no influence on introductory teaching with Java. Some, however, will become visible even close to the beginning of programming. Here, I give a short overview of what’s new, and what you — as a teacher of introductory programming — should be aware of.

Java 7 – What’s new

Most of the new features in Java 7 are under the hood or in specialised libraries. These are very unlikely to affect an introductory programming course.

Improvements to the internals of the JDK include changes to the VM to support dynamically typed languages and improvements to the class loader architecture. On the library side, there are new frameworks for concurrency, cryptography and new versions of JDBC and Unicode. All these will not be relevant for most introductory courses.

The two areas that are relevant are “Project Coin”, the code name given to a project defining several small language enhancements, and NIO.2, a new library for I/O. We’ll discuss these in more detail in a moment.

Equally important, what’s not included in this release includes support for closures (known as “Project Lambda”). This would have been the most significant change to Java since the introduction of generics in Java 5 or, arguably, since the original definition of the Java language in 1995. Project Lambda has, however, been deferred to JDK 8 in what’s known as Plan B. JDK 8 is currently scheduled for release in late 2012.

So, which of the new Java 7 features are actually relevant for our intro programming course?

NIO.2

The I/O classes in Java have been improved several times over the years. The release of JDK 1.4 in 2002 brought some significant improvements in the somewhat short-sightedly named NIO library. The naming is rather less than ideal, since it stands for “New I/O”, and the passing of time dictates that everything new will eventually get old.

Which brings us to Java 7 and the New New I/O. So what will this be called now — NNIO? Well, the designers settled on NIO.2.

NIO.2 brings a number of new classes and interface, some with very useful methods. If you are doing any programming that accesses the file system, it’s worth familiarising yourself with these. Particularly interesting are the Files and Paths classes, and the Path interface, which you can find in the java.nio.file package.

All other relevant new features are part of Project Coin. They are diamond notation, strings-in-switch and improved exception handling.

Project Coin

Diamond notation

Generic type details on the right hand side of an assignment can now be inferred. For example, where in Java 6 we had to write

   HashSet<String, Monster> monsters = new HashSet<String, Monster>();

to declare a HashSet variable and initialise it with a fresh HashSet object, in Java 7 we can write

   HashSet<String, Monster> monsters = new HashSet<>();

In other words: We do not have to repeat the generic types of the HashSet on the right hand side, and can instead just write <>. (This syntax is the reason that this construct is known as the “diamond notation”). The effect of this is exactly as the Java 6 version above. It is a purely syntactic shortcut. The compiler will fill in the generic types by copying them from the variable declaration on the left, and all behaves just as before. Of course, the old notation is still allowed.

Strings in switch statements

The variable used in switch statements can now be of type String. For example

   switch (command) {
       case "go":
          goForward();
          break;
       case "help":
          showHelp();
          break;
       default:
          unknownCommand();
          break;
   }

Before Java 7, strings could not be used in switch statements.

Improved exception handling 1: multi-catch

It is now possible to catch multiple exceptions in a single exception handler. For example:

   try {
      file = new File("readme.txt");
      process(file);
   }
   catch (FileNotFoundException | UnsupportedEncodingException ex) {
      ...
   }

As you can see in this example, the catch clause can list multiple types of exception in its header, separated with an OR symbol, to catch any of these types of exception.

Improved exception handling 2: try-with-resources

The second new feature relating to exceptions is called try-with-resources. It solves a hard problem: It was previously surprisingly hard to correctly guarantee that resources (such as files or network connections) were correctly closed in the case of an exception.

The new construct solves this. Look at this example:

   try (FileWriter writer = new FileWriter(filename)) {
      ...
   }
   catch (IOException e) {
      ...
   }

Before Java 7, the standard way to close a resource (a FileWriter in this example) would have been in a finally block, which followed the catch block. In Java 7, the FileWriter is opened in round brackets following the try keyword, marking it as a resource to be auto-closed. Once the try/catch block is completed, the resource will automatically be closed by the Java runtime system.

For classes to be used with the auto-close mechanism, they must implement the new AutoCloseable interface. All the relevant classes in the Java library have been retrofitted to implement this interface.

That already sums up the relevant Java 7 changes. As we can see — not much to worry about here. (This will be different next year, when JDK 8 will bring us closures. I expect we will have to have a lively discussion then about how to treat these in a first-year course. But we can leave that for a while.)

To find out more about the new constructs in Java 7, see this summary. The next version of the Object First book (5th edition, to be released in late October) includes discussion of these new features.


Note: This post was first published in the Blueroom.

Multiple levels in Greenfoot games

A demo scenario

Yesterday I announced that a new Greenfoot version is available (version 2.1). Over the next few days, I’ll go through some of the new features and introduce them briefly here. This is the first one: the setWorld(…) method.

The Greenfoot class now has a method with the following signature:

setWorld (World world)

This method takes a world object as a parameter, and it will show that world in the Greenfoot main window.

This allows you to have multiple World subclasses (in my example called Level1 and Level2). You can then dynamically (that is: while your program is running) create and install other world objects. These other worlds can show entirely different scenes, such as other levels.

Two world subclasses, representing different levels.

For example, to go to Level 2, you could use the following statement:

   Greenfoot.setWorld(new Level2());

Of course, the same initialisation applies as usual: If the Level2 world creates and inserts some actors in it’s constructor, this will all happen.

One thing to keep in mind, though, is that this will – if you don’t do anything clever – create new actors. So, if you have a game character in level 1, an then you add a game character to level 2, you will have a new character object. If you stored some state (e.g. a score) in the instance variables of that actor, it will be gone. If you want to preserve the state of your game character, make sure you carry the actor object across without creating a new one.

An example showing this new functionality in action is now on the Greenfoot Gallery, here.

Greenfoot 2.1 released

We have just released Greenfoot version 2.1.0.

This update of Greenfoot includes a good number of bug fixes, so if there is something that has bugged you for a while, give the new version a go and see whether it’s improved. (If not, tell us!)

But, more importantly, this version also includes some new functionality. The new features include:

  • A new sound API for volume control. This means Greenfoot scenarios can programmatically adjust the volume of sound clips. Several people have asked for this, especially aiming at fading sounds in and out nicely.
  • A new input function: getMicLevel. This function returns the noise level from the system microphone. This makes it very easy to write soem very simple early interactive examples.
  • Support for multiple worlds. Greenfoot now has a function to dynamically show different world objects. This makes it much easier to develop games with different levels.
  • Built-in move and turn methods. Actors in Greenfoot now have turn(int) and move(int) methods which turn and move relative to the current rotation.
  • UI changes. Finding out how to share your scenario on the Greenfoot Gallery has been made much easier. We suspect that many users previously never discovered this important function.

So, surf over to the Greenfoot download page and give it a go. Let us know what you think.

Over the next few days, I will add a few blog posts here that introduce and explain the new functionality in more detail. So check back soon!

Part 1: Using setWorld to create multiple game levels.

Use the Microsoft Kinect with Greenfoot

Those of you who know Greenfoot know that one of its aims is to make programming for beginners exciting and engaging. (Those of my readers who don’t know it should have a look here.)

The most recent addition to Greenfoot is a library that allows programmers to easily use the Microsoft Kinect module with their Greenfoot scenarios. This means that you can now write simple Greenfoot games that are controlled by players body movements.

Probably the easiest way to show what I mean, is to show you what I mean. Here’s a short video:

Programming the Kinect with Greenfoot is probably the easiest way to write programs with the Kinect module. Neil Brown, one of our developers on the Greenfoot team, has adapted open source server software that communicates with the Kinect and designed and implemented a Greenfoot library that makes access surprisingly simple.

If you are interested to try it yourself — here are the detailed instructions. But beware: you might stand in the middle of your room waving your arms around for the next few days! Some people might look at you strangely, but it’s great fun.