Classes and Objects, Part One

This is the eighth lesson in a series introducing 10-year-olds to programming through Minecraft. Learn more here.

One of the most important topics Java we need to understand in for modding Minecraft is classes and how to use them.

A class is a definition (or blueprint) for an object. It is a grouping of variables (called fields) and methods.

public class Block
    private String unlocalizedName;

    public final int blockID;

    /* Number of hits it takes to break a block. */
    public float blockHardness;

    public Block(int id, Material par2Material) 

    protected void initializeBlock() 

    public void setStepSound(StepSound sound) 

This class has:

  • 3 fields: unlocalizedName, blockID, and blockHardness. Fields are simply variables within a class.

  • 3 methods: Block (which is a special method called a constructor since it has the same name as the class), initializeBlock, and setStepSound. A method is a group of statements that perform a specific task. The variables listed within parentheses after a method name are called parameters.

Creating Objects

To create an object (an instance of a class), we use the new keyword.

Block myBlock = new Block(...);

We can then access methods and fields that are part of the class definition.

myBlock.setStepSound(new StepSoundSand(...));

myBlock.blockHardness = 4.0f;

Note that we can only access methods and fields that are marked public. We will talk more about visibility later.


Let's say we have a Block class that can already perform a bunch of tasks. We might want to create a special type of snow block that melts if a player stands on it for too long.

Since we don't want to copy all the code we have in Block into our new BlockSnow class, we can have BlockSnow extend Block. (We could also say that BlockSnow is derived from Block or that BlockSnow inherits from Block).

What this means is that we automatically get all of the functionality of Block in BlockSnow and we can add some new functionality as well.

public class BlockSnow extends Block 
    public void melt() { ... }

BlockSnow blockOfSnow = new BlockSnow();

Note that although we didn't include setStepSound in our BlockSnow class, we can still call that method because it exists in the parent class (Block).

comments powered by Disqus