2024_Programming_Training_D.../CS7 - Challenge Solution/Ball.java

56 lines
1.6 KiB
Java

//A class based representation of a ball
public class Ball {
//3 instance variables, the first, diameter,
//stores the diameter of the ball in whatever
//units you want.
//The second, a String representation of the color
//of the ball.
//The third, an integer that stores the number
//of times the ball has been bounced.
private double diameter;
private String color;
private int timesBounced;
//Constructor to create balls with, specifying
//the diameter and color of the ball.
//Note that timesBounced is set to 0,
//this constructor assumes that this is a fresh
//ball that has never been bounced.
public Ball(double newDiameter, String newColor) {
diameter = newDiameter;
color = newColor;
timesBounced = 0;
}
//Returns the current diameter of the ball
public double getDiameter() {
return diameter;
}
//Returns the current color of the ball
public String getColor() {
return color;
}
//Returns the number of times this ball has
//been bounced
public int getTimesBounced() {
return timesBounced;
}
//Bounces the ball, all this does is add
//one to the timesBounced instance variable
public void bounceBall() {
timesBounced++;
}
//A normal toString method, that provides the
//instance information about the Ball that we
//are currently working with as a String
public String toString() {
return "This ball is " + color + " with a diameter of " +
diameter + " and has been bounced " + timesBounced +
" times!";
}
}