This is the ninth lesson in a series introducing 10-year-olds to programming through Minecraft. Learn more here.
Let's take a closer look at our Block
class.
package net.minecraft.block;
public class Block
{
public static final StepSound soundWoodFootstep =
new StepSound("wood", 1.0F, 1.0F);
public float blockHardness;
protected Icon blockIcon;
private String unlocalizedName;
public Block(int id, Material material)
{
...
}
protected void initializeBlock()
{
...
}
public void setStepSound(StepSound sound)
{
...
}
}
Packages
Every class
is contained in a package
. If we're creating a new kind of Block
(e.g. RiverBankBlock
) in our own package (e.g. mc.jb.first
), then we need to import the package that Block
lives in.
Our source code file, RiverBankBlock.java
might look like this:
package mc.jb.first;
import net.minecraft.block;
public class RiverBankBlock extends Block
{
....
}
If we didn't include the import
statement, the compiler would get confused because it wouldn't know where to find the class definition for Block
.
Visibility
Parameters: Method parameters are only accessible within a given method. In our Block
class, there is no way to use the sound
parameter from the setStepSound
method in the initializeBlock
method.
Fields: All fields defined in a class are accessible in any method within that class.
Derived classes: Only fields marked public
and protected
in a parent class are accessible in child classes. Our RiverBankBlock
class could access blockIcon
and blockHardness
from Block
, but not unLocalizedName
.
Non-derived classes: If we create an object ourselves (using the new
keyword), we only have access to its public
fields and methods.
Lifetime
In general, we won't need to worry too much about how long an object exists. However, there is a special keyword called static
that we will come across while creating mods.
Static method: A method that can be called without creating an instance of the class. Here's a class with static methods we'll use when creating our own type of block:
public class MinecraftForge
{
public static void setBlockHarvestLevel(
Block block,
String toolClass,
int harvestLevel)
{
....
}
}
To call this method, we use the name of the class itself rather than an instance (variable) name.
Block block = new Block();
MinecraftForge.setBlockHarvestLevel(
block, ....);
Static field: A field that can be accessed without creating an instance of the class.
Looking back at our Block
example, if we want to call setStepSound
, we first need to have an instance of Block
either as a method parameter or as a variable we created ourself.
However, anyone can use the public
field soundWoodFootstep
"directly", like this:
StepSound sound = Block.soundWoodFootstep;
Comments