Can't see me
Can't see me

Reputation: 501

Implementing Classes Java

Question in book: Write a class Battery that models a rechargeable battery. A battery has a constructor public Battery(double capacity) where capacity is a value measured in milliampere hours. A typical AA battery has a capacity of 2000 to 3000 mAh. The method public void drain(double amount) drains the capacity of the battery by the given amount. The method public void charge() charges the battery to its original capacity. The method public double getRemainingCapacity() gets the remaining capacity of the battery.

My Question: Are my instance variables right? How do you figure out what needs to be in the private instance variables? (If that makes sense) Can this code be written in a better way?

My Code:

public class Battery
{

      private double fullCharge;
      private double batteryCapacity;

public Battery(double capacity)
{

      batteryCapacity = capacity;
      fullCharge = capacity;

}
public void drain(double amount)
{
     batteryCapacity = batteryCapacity - amount;
}

public void charge()
{

     batteryCapacity = fullCharge;
}

public double getRemainingCapacity()
{
     return batteryCapacity;
}

}  

Upvotes: 3

Views: 2712

Answers (6)

Joohwan
Joohwan

Reputation: 2512

Seems pretty good to me.

You declare variables private when you don't want anyone to change them from outside of the class in an unexpected manner. For example, by utilizing accessor methods you can restrict access to your private variables (e.g. get method but no set method).

Also, for people who want to use your code but are still unfamiliar with it, you provide them an extra level of indirection/protection which prevents them from carelessly screwing things up by forcing them to use the public methods to access private variables.

So one could say that if you knew exactly what you were doing all the time and you were the only one using your code, you wouldn't need private variables at all. But no one is perfect. We sometimes forget what the classes we wrote years ago are supposed to do, and one's code is often used by many, and private variables (along with countless other features) are there to provide structure and a standard which everyone can follow and agree on.

Upvotes: 1

Andromeda
Andromeda

Reputation: 1368

Your code with minor error checking additions.

public class Battery
{
      private final int MAX_BATTERY_LIMIT = 3000;
      private double fullCharge;
      private double batteryCapacity;


public Battery(double capacity)
{
     if(capacity <=  MAX_BATTERY_LIMIT)
     { 
         batteryCapacity = capacity;
         fullCharge = capacity;
     }
     else
     {
          throw new IllegalArgumentException("battery capacity out of range: " + this.batteryCapacity +  " expected range 0 <= batteryCapacity < " +            MAX_BATTERY_LIMIT);

     }

}
public void drain(double amount)
{
     batteryCapacity = batteryCapacity - amount;
     if(batteryCapacity < 0) 
      batteryCapacity = 0;
}

public void charge()
{

     batteryCapacity = fullCharge;
}

public double getRemainingCapacity()
{
     return batteryCapacity;
}

} 

Upvotes: 1

Aniket Thakur
Aniket Thakur

Reputation: 68935

Are my instance variables right?

Looks good.

How do you figure out what needs to be in the private instance variables? 

You make your variables private when you do not want users to directly operate on them . Operation should be only by the public functions you have provided(like getters/setters).

Can this code be written in a better way?

One way I think is to check for edge cases.

public class Battery {

private double fullCharge;
private double batteryCapacity;
private static double maxCapacity = 100;  //some value

public Battery(double capacity) {
    if (capacity > maxCapacity) {
        throw new RuntimeException("Exceeding max battery charge capacity");
    }
    batteryCapacity = capacity;
    fullCharge = capacity;
}

public void drain(double amount) {
    double tempBatteryCapacity = batteryCapacity - amount;
    if (tempBatteryCapacity < 0) {
        batteryCapacity = 0;
    } else {
        batteryCapacity = tempBatteryCapacity;
    }
}

public void charge() {

    batteryCapacity = fullCharge;
}

public double getRemainingCapacity() {
    return batteryCapacity;
}

}

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

All looks good to me except the fact that you are missing a validation of battery capacity between 2000-3000 mAh. So make sure when you try to set the capacity, the value is in the valid range.

Couple of changes you need to do the validations:

  1. Update constructor to put in a validation for capacity and throw an exception in case the value is out of range
  2. Update your drain method to make sure, it does not make the capacity to run negative.

I am writing the code here directly so please excuse me for any error, change it as per you need or to remove any compilation problem:

public class Battery
{

      private final double fullCharge;
      private double batteryCapacity;

public Battery(double capacity)
{

      if(capacity < 2000 || capacity > 3000)
          throw new Exception("Cannot create Battery as the capacity should be in betweeen 2000 and 3000");
      batteryCapacity = capacity;
      fullCharge = capacity;

}
public void drain(double amount) throws Exception
{
     if((batteryCapacity - amount) < 0 || (batteryCapacity - amount) > 3000) 
         throw new Exception("The amount is invalid as the battery capacity is going out of range");
     else 
              batteryCapacity = batteryCapacity - amount;
}

public void charge()
{

     batteryCapacity = fullCharge;
}

public double getRemainingCapacity()
{
     return batteryCapacity;
}

}  

Upvotes: 0

Harikrishnan
Harikrishnan

Reputation: 21

Your instance variable seems pretty good.

Generally most of the instance variable are made private and if and only if it seems that making an instance variable private makes no sense or doesn't provide any profit you make it as public.

Use compound assignment operator in the method drain()

batteryCapacity -= amount;

You can update the methods and constructors to check the range(for negative values).

Upvotes: 2

Rahul Tripathi
Rahul Tripathi

Reputation: 172438

Yes all looks good.

How do you figure out what needs to be in the private instance variables?

Private Instance variables are used to force the users of those class to use methods to access them. You can use Properties to get and set the values.

Upvotes: 0

Related Questions