...

/

Classes define objects

Classes define objects

A class is used to define the custom data structure that makes up an object of that class.

We have seen that classes are the organizational unit of a Java program. Source code for methods is always within a class, and we might expect related methods to be in the same class.

However, classes do much more than this, and are the heart of object-oriented programming in Java:

  1. A class is used to define the custom data structure that makes up an object.
  2. Classes define methods that act on those objects.

Here’s an example of creating a custom data type, Circle, to store information about a circle:

Press + to interact
// include educative's simple graphics library:
import com.educative.graphics.*;
class Circle {
public int x;
public int y;
public int r;
}
class CircleTest {
public static void main(String[] args) {
Circle circ; // declare a variable to store a reference to Circle object
// create a new Circle object in memory, and store a reference to it:
circ = new Circle();
// set values for the instance variables for the circle:
circ.x = 100;
circ.y = 100;
circ.r = 50;
// Create a Canvas object for drawing on the screen:
Canvas c = new Canvas(200, 200);
c.fill("yellow");
c.stroke("black");
// use instance variables of the the circle object when calling
// the circle method of the canvas (used to draw the circle)
c.circle(circ.x, circ.y, circ.r);
}
}

Notice that there are two different classes defined in this file. Typically in Java, each class would get its own file, with the name of the file ClassName.java. So Circle might be defined in a class Circle.java. This is a good convention and we should follow it; the classes are in the same file here only because it is easier to read on the web page.

A class declares what instance variables an object of that class will contain

Just like in Javascript, Python, or C++, an object is a data structure stored on the heap area of memory, containing data elements. ...