In: Computer Science
This code in java:
A typical ball is circular in shape. Many games are played with ball e.g cricket ball football etc. Impingement a scenario in which you create cricket ball and football or any other game ball. All balls differ in color, size and material
I have created a ball class, that represents the ball in general. A ball can be represented by its properties, like size, color, material, game, etc. As these properties are defined, we get the purpose of the ball. Similarly we can define a ball class having above properties. These properties of a ball can be set when defining a new ball object, or after the object is defined. once we have a ball class, we can define different objects representing different types of balls.
I have attached relevant comments in the example code below. I hope you find it helpful.
As an example, I have created two sample ball objects, cricketBall and football representing actual game balls.
public class ball {
public static void main(String[] args) {
Ball cricketBall = new Ball("cricket", "leather", "white", 10);
Ball football = new Ball("football", "synthetic", "white", 50);
System.out.println(cricketBall.getColour());
System.out.println(football.getColour());
}
}
class Ball {
//colour of the ball
private String colour;
//size of the ball in cm
private int size;
//material of the ball
private String material;
//game where the ball is used
private String game;
//initialise the ball(any kind) with the following properties
Ball(String game, String material, String colour, int size) {
this.colour = colour;
this.game = game;
this.size = size;
this.material = material;
}
/**
* @return returns colour of the ball
*/
public String getColour() {
return colour;
}
// sets the colour of the ball
public void setColour(String colour) {
this.colour = colour;
}
//returns the size of the ball
public int getSize() {
return size;
}
// sets size of the ball
public void setSize(int size) {
this.size = size;
}
//returns the material of the ball
public String getMaterial() {
return material;
}
//sets the material of the ball
public void setMaterial(String material) {
this.material = material;
}
//returns the game where the ball is used
public String getGame() {
return game;
}
//sets the game property of the ball
public void setGame(String game) {
this.game = game;
}
}