0

So Currently, our Key class can only produce white keys. This is because I have hard-coded the file names of the key images ("white-key.png" and "white-key-down.png"). How do I use abstraction to modify the Key class so that it can show either white or black keys?

import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

public class Key extends Actor
{
    private boolean isDown;
    private String key;
    private String sound;
    /**
     * Create a new key.
     */
    public Key(String keyName, String soundFile)
    {  
       key = keyName;
       sound = soundFile;
    }

    /**
     * Do the action for this key.
     */
    public void act()
    {
        if ( !isDown && Greenfoot.isKeyDown(key)) 
        {
            play();
            setImage("white-key-down.png");
            isDown = true;
        }
        if ( isDown && !Greenfoot.isKeyDown(key))
        {
            setImage("white-key.png");
            isDown = false;
        }
    }

    /**
     * Play the note of this key.
     */
    public void play()
    {
        Greenfoot.playSound(sound);
    }
}

1 Answers1

0

I understand from your question that you want different classes that have different images, rather than an option for changing the image within the same class.

There are several ways to do this; here's a simple one just to give you an idea:

import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

abstract public class Key extends Actor
{
    private boolean isDown;
    private String key;
    private String sound;

    abstract String getImageFileName();
    abstract String getDownImageFileName();

    /**
     * Create a new key.
     */
    public Key(String keyName, String soundFile)
    {  
       key = keyName;
       sound = soundFile;
    }

    /**
     * Do the action for this key.
     */
    public void act()
    {
        if ( !isDown && Greenfoot.isKeyDown(key)) 
        {
            play();

            String image = getDownImageFileName();
            setImage(image);

            isDown = true;
        }
        if ( isDown && !Greenfoot.isKeyDown(key))
        {
            String image = getImageFileName();
            setImage(image);
            isDown = false;
        }
    }

    /**
     * Play the note of this key.
     */
    public void play()
    {
        Greenfoot.playSound(sound);
    }
}

Then you can add new classes, each with its own image:

public class WhiteKey extends Key
{
    @Override
    String getImageFileName()
    {
        return "white-key.png";
    }

    @Override
    String getDownImageFileName()
    {
        return "white-key-down.png";
    }
}

public class BlackKey extends Key
{
    @Override
    String getImageFileName()
    {
        return "black-key.png";
    }

    @Override
    String getDownImageFileName()
    {
        return "black-key-down.png";
    }
}
Yehuda Shapira
  • 8,460
  • 5
  • 44
  • 66