Hey guys,

Im having some problems with an exercise that I need to complete with the use of inheritance - In the exercise I am concerned with two Classes (Cupboard and Safe). The cupboard can be opened and closed and tested to see if it is open or not. A safe is similar to a cupboard except that it can be locked and unlocked.
So by using inheritance I need to develop the Safe class further so that it inherits methods of the cupboard class (like open, and close), but also add local methods to the Safe class such as lock and unlock.

I have made progress but I am not entirely sure Im on the right track as the software that is marking the excersise is complaining about a number of certains aspects (like Safe() constructed incorrectly etc)

Heres the Code

Cupboard (already provided)

public class Cupboard {
    protected boolean open;         // save the open/closed state

    public Cupboard() {         // Constructor - cupboards arrive false!
        open = false;
    }

    public boolean isOpen() {           // test if Cupboard open or closed
        return open;            // returns true if open
    }

    public void openDoor() {        // open the cupboard
        open = true;       
    }
    
    public void closeDoor() {       // close the cupboard
        open = false;
    }
}

Safe (What I need to develop)

import java.io.*;

public class Safe extends Cupboard
{
    protected boolean safeOpen;
    protected int safeCombination;
    
    public Safe(int theCombination)
    {
       //safeCombination = theCombination;
        safeOpen = false;        
    }//endConstructor
        
    public void lock()
    {
        boolean doorOpen;
        
        doorOpen = isOpen;
        
        if(doorOpen == true)
        {
            closeDoor();
            safeOpen = false;
        }//endIF
        else
        {
            safeOpen = false
        }//endElse
    }//endmethod
        
    public void unlock(int theCombination)
    {
        safeOpen = true;
        //openDoor();
    }//endmethod
    
    public boolean isLocked()
    {
        return safeOpen;
    }//endmethod
    
    /*public static void main(String[] argv)
    {
        int userI;
        Safe newSafe = new Safe(1234);
        
        UserInput.prompt("Enter PIN: ");
        userI = UserInput.readInt();

        newSafe.unlock(userI);
    }//endMainMethod */
   
}//endclass

Any suggestions would be appreciated.

Thanks

Recommended Answers

All 2 Replies

I see no errors... you're ignoring the 'open' variable inherited from the Cupboard class, though.

Maybe bad naming? safeOpen seems to mean safeLocked in some of the methods, but is used redundantly for the inherited open variable in others.
(And the unlock method needs to check the combination before unlocking.)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.