javaclasstest-class

how to implement methods in a test class?


I made this class but I cannot find a way to make the test class and implement the methods I used.

public class Battery
{      
       private float fullCharge = 3000;
       private float batteryCapacity;
       public Battery (float capacity)
       {
            if(capacity >0) 
            batteryCapacity = capacity;
            fullCharge = capacity;          
       }  
       public void drain (float amount)
      {
             batteryCapacity = batteryCapacity -= amount;
       }
       public void charge (float amount)
       {
             batteryCapacity = fullCharge;
       }
       public float getRemainingCapacity()
       {
             return batteryCapacity;
       }
}

Solution

  • Your method implementations are almost correct. But there are a few minor errors.

    First I guess when you say:

    if(capacity >0)
    batteryCapacity = capacity;
    fullCharge = capacity;  
    

    You actually mean:

    if(capacity >0) {
        batteryCapacity = capacity;
        fullCharge = capacity;
    }  
    

    In your drain method, you decresed the batteryCapacity wrongly. It's just:

    batteryLeft -= amount;
    

    In your charge method, you didn't use the paramter amount so I think it's better to delete taht paramter. Alternatively, You can add the amount to batteryCapacity like this

    batteryCapacity += amount;
    

    I hope this helps. By the way I think you should name your batteryCapcity variable to something like batteryLeft to increase clarity.