...

/

Classes contain methods

Classes contain methods

Classes contain the code for methods that act on objects; methods have access to the object using the special variable "this".

Here is some code to create a custom Ball class that is used to store information about a ball that will bounce on the screen. The main method of BallExample creates a Ball object using the new keyword and a call to the constructor. Read the code carefully now:

Press + to interact
import com.educative.graphics.*;
class Ball {
public String color;
public int x;
public int y;
public int vx;
public int vy;
public Ball(String color, int x, int y, int vx, int vy) {
this.color = color;
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
}
}
class BallExample {
public static void drawBall(Canvas canvas, Ball ball) {
canvas.fill(ball.color);
canvas.stroke("black");
canvas.circle(ball.x, ball.y, 10);
}
public static void main( String args[] ) {
Canvas c = new Canvas(200, 200);
// create a red ball at location (20, 30) with 0
// x and y velocity:
Ball b = new Ball("red", 20, 30, 0, 0);
drawBall(c, b);
}
}

The BallExample class also has a ...