Objects practice

posted by: Ms. Martin 2 February 2011 No Comment

Implement a class Car with the following properties and methods:

  • fuel efficiency (measured in miles/gallon or liters/km — pick one and make sure to specify it in your comments)
  • mileage
  • fuel tank capacity (again, pick your units)
  • current fuel level
  • constructor that allows the user to set efficiency, mileage and tank capacity. Fuel level should be set to 0.  Throw IllegalArgumentException as appropriate.
  • drive method that simulates driving for a certain distance, reducing the gasoline in the fuel tank (you may assume that drive is never called with a distance that consumes moree than the available gas)
  • getGasInTank method that returns the current amount of fuel
  • addGas method that adds gas to the tank (throw an IllegalArgumentException if it exceeds capacity!)

Sample usage:
Car myHybrid = new Car(50, 20000, 15); // 50 miles per gallon, 20,000 miles and 15 gallon tank (no gas in tank)
myHybrid.addGas(15); // pump 15 gallons of gas
myHybrid.drive(100); // drive 100 miles
double gasLeft = myHybrid.getGasInTank(); // get gas remaining in tank
Create a class that tests all of your methods by creating a couple of different cars. Make sure you test all cases (ex: adding more gas than the tank has space for).


In a system like The Source, student information is stored in a database.  Every time student information is requested, an object is most likely built from the database information.  We’re going to design and build a Student class.

This is a little unusual (as in it’s probably not the kind of thing your boss would ask you to do), but should serve as good practice — I am giving you the client code from which you need to write the class from which to build appropriate objects.  Download StudentGrades.java and write Student.java from it.  You may want to comment out certain parts of StudentGrades.java in order to test one piece of your class at a time.  Note that grades are stored in an array initialized in the constructor.

It should never be possible for a student to have a negative score.  In order to enforce this, you need to make sure no one can break encapsulation and change a field directly… you should also throw exceptions as needed.

1 Star2 Stars3 Stars4 Stars5 Stars (7 votes, average: 2.71 out of 5)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>