Search code examples
javaoopinstantiationminecraftinstances

Can anyone help me with how to use interfaces?


It is for a Minecraft plugin (though it's just to try to figure out how they work); thus, it's only for practice, in a sense. I can't figure out how to use the instance Explosive of the class Explosive of the package net.canarymod.api.entity. Any help on what I'm doing wrong or should be doing would be greatly appreciated. If it's of any concern, I'm using the CanaryMod API. Here's the code:

import net.canarymod.api.entity.Explosive;

public class main {

    public static void main(String args[]){
        Explosive explosion = new Explosive();
        explosion.setPower(300);
        explosion.setCanDamageWorld(false);
        explosion.setCanDamageEntities(true);
        System.out.println(explosion.canDamageWorld());
    }
}

Solution

  • I do agree that it would be a good idea to look at a tutorial, but I can give you a little start on the concept of Interfaces.

    Interfaces aren't actually classes that can be instantiated as objects. They don't contain any logic about how to do anything, all they contain is method signatures. Another class can implement an interface, and the point of that is that the implementing class is required to implement each of the methods mentioned in the interface.

    So, for your example (and I'm just going off of a thing I googled here, and my understanding of minecraft as a game -- I haven't written mods for it): EnderCrystal, LargeFireball, TNTPrimed, and WitherSkull all implement Explosive. That means all four of those have their own implementations of the various methods that Explosive defines. They can each do anything that an Explosive can do, and any other things they defined for themselves.

    The neat thing is that because of the way interfaces work, your code is very very close to working. All you need to do is change line 6 so that you're creating a new one of those other classes (your explosion can even keep its type, because whichever one of those four you choose, it will also be of type Explosion, in addition to being the more specific sub-type).