Classes and objects in Java
One of the ideas behind object-oriented software is to organize software in a way that matches how an object-oriented mind thinks. Instead of machine instructions that change bits in main memory, we want "things" that "do" something. Of course, nothing has changed at the machine level; bit patterns are still changed by machine instructions. The change is that we don't have to think that way.
Question: Name a few objects.
A pencil, a keyboard, shoes, a table
Question: What characterizes an object?
- An object is made of tangible material
- An object behaves as a whole, made of parts
- An object has properties
- An object can do some things, and some actions can be done to it.
The first item in this list is too restrictive. There can also be objects that are not tangible. Think of your bank account. Although it is not a material thing, the account has its properties (balance, owner) and you can do some things with it (withdraw money, close it). Accordingly, we can say that an object:
- has identity (behaves as a whole)
- has state (has properties that can change)
- has behavior (can do some things, and some actions can be done to it)
An object has state, behavior and identity. The structure and behavior of similar objects are defined by their common class.
YOU CAN FIND EXAMPLES FROM THIS AREA ON THE FOLLOWING WEB PAGE: Classes and objects – examples (SR)
Video lessons
VIDEO 1: Classes and objects in Java
Classes and objects, Java, programming, object-oriented programming, points in the plane, constructors, object methods,
VIDEO 2: Objects and methods in Java
Methods as part of an object. Methods that return and don't return a value. Defining and calling methods. Calling methods from imported classes.
VIDEO 3: Static variables and methods
Static variables. Variables as properties of a class. Static methods. The difference between variables as properties of an object and static variables. An example with squares and triangles
VIDEO 4: Encapsulation. Getters and setters
How encapsulation of an object is done in Java and what it means. Hiding the attributes of an object. Using getters and setters in a class.
VIDEO 5: Visibility of data in a class
The difference between local data, defined in a method, and the fields of a class.
Complex data – objects
To reserve memory for an object we use the following pattern:
data_type data_name=new constructor(constructor_parameters);
For the data type we use the name of the class the object belongs to. E.g. if the object belongs to the class Scanner, the definition of that object, which we will call ucitavac (reader), would be:
Scanner ucitavac=new Scanner(System.in);
Defining complex data.
software objects imitate objects in nature, so both have:
- Properties
- Behavior
- State
A class as a description of an object
The class of an object is actually a description of all objects that belong to it, i.e. objects that have the same:
- Properties
- Behavior – described by methods
By defining an object, we created it according to the description (the class), and it will have the properties and methods listed there:
Methods of the Scanner class
The Scanner class has some methods, for example:
- nextInt() – this method takes from standard input the data the user typed on the keyboard and converts it into an integer.
- nextDouble() – this method takes from standard input the data the user typed on the keyboard and converts it into a real number.
Objects in nature and software objects have
- identity (behaves as a whole)
- state (has properties that can change)
- behavior (can do some things, and some actions can be done to it)
Software objects have identity because they take up a separate part of memory. A software object is unique, even if it looks the same as another object.
Software objects have state. Part of the memory a software object takes up is used for variables that hold values.
Software objects have behavior. Part of the memory they take up is used to store methods (programs) that let the object "do something". An object does something when one of its methods runs
Suppose we take as the object the initial dialog window of the application shown

The next picture shows this object in memory

From the picture of this object in memory we conclude:
- The bricks in the picture are the bytes of memory the object takes up.
- This object has some variables, sirinaDijaloga (dialog width), visinaDijaloga (dialog height) and textUNaslovu (title text), as well as some methods that control its behavior
- A software object consists of variables and methods
The class of an object
- A class is a set of objects that have a common structure and behavior.
- One object is an instance of a class
- The common properties of objects and the methods that represent the behavior of those objects are described in their class
Classes and objects: points in the plane
Task text: Create 3 objects that represent three points in the plane, A, B, C. Move point A to a new position A1.
§Show the coordinates of the points after the move. The data of the points are given in the picture.
A(2,4)
B(5,-2)
C(-4,2)
A1(1,3)
Notice that all three objects belong to the same class because they have the same properties x and y. They will be 3 different instances (objects) of the same class
The state of point A will change during the program, but its properties will not.
To create the objects, we first have to create a class that describes them. We will call the class Tacka (point). In it we will list the common attributes x and y that all 3 objects will have.
The Tacka (point) class
public class Tacka {
double x;
double y;
}
public class TakeURavni {
public static void main(String[] args) {
// here we write the code of the main program
}
}
Let's create the main class and go to the start of the main method
public class TakeURavni {
public static void main(String[] args) {
Tacka A = new Tacka();
Tacka B = new Tacka();
Tacka C = new Tacka();
}
}
Let's create all three objects, i.e. reserve memory for them, using the class Tacka as the description

To get to the properties of the created objects we use the operator ”.”

In the list that opened we can see the properties and methods described by the class Tacka. We can also see some inherited methods; we will talk about inheritance later
public class TakeURavni {
public static void main(String[] args) {
Tacka A = new Tacka();
Tacka B = new Tacka();
Tacka C = new Tacka();
A.x = 2;
A.y = 4;
B.x = 5;
B.y = -2;
C.x = -4;
C.y = 2;
Now we will set all the coordinates as shown in the picture on the left.
public static void main(String[] args) {
Tacka A = new Tacka();
Tacka B = new Tacka();
Tacka C = new Tacka();
A.x = 2;
A.y = 4;
B.x = 5;
B.y = -2;
C.x = -4;
C.y = 2;
A.x = 1; // point A moves to position A1(1, 3)
A.y = 3;
}
To move point A to the new position, we set new values of x and y for object A, and at the end the data about the points are shown:
public class TakeURavni {
public static void main(String[] args) {
Tacka A = new Tacka();
Tacka B = new Tacka();
Tacka C = new Tacka();
A.x = 2;
A.y = 4;
B.x = 5;
B.y = -2;
C.x = -4;
C.y = 2;
A.x = 1;
A.y = 3;
System.out.println("A(" + A.x + "," + A.y + ")");
System.out.println("B(" + B.x + "," + B.y + ")");
System.out.println("C(" + C.x + "," + C.y + ")");
}
}
Program output: A(1.0,3.0), B(5.0,-2.0), C(-4.0,2.0) – each point in its own line.
Example: Geometric shapes
Task text:Create objects for two squares and one circle. Enter the sides of the squares and the radius of the circle and compute their areas.Solution:
Since the two objects that represent squares have the same properties, the side a and the area P, we can say that they belong to the same class, the class that describes any square. We can name this class e.g. Kvadrat (square) or Opis_Kvadrata (square description), and this "description" will apply to any square.
On the other hand, the object that represents the circle does not have the same properties as a square, so it belongs to another class, which we can call e.g. Krug (circle) or Opis_Kruga. There is also the "main" class, from which the program starts and which has the main method. Let this class have the same name as the project: GeometrijskiOblici (geometric shapes). The objects are created and the flow of the whole program is controlled inside this class. The classes are created as follows. The class Kvadrat has the attributes of a square: a (side), P (area) and an empty constructor.
The next lesson covers methods, as parts of classes, and class constructors: Methods and objectsThe class Kvadrat:
package geometrijskioblici;
public class Kvadrat {
double a; //The side of the square as a field or attribute of the class
double P; //The area of the square as a field or attribute of the class
//Constructor without parameters
public Kvadrat() {
}
}
The class Krug:
package geometrijskioblici;
public class Krug {
double r; //The radius of the circle as a field or attribute of the class
double P; //The area of the circle as a field or attribute of the class
//Constructor without parameters
public Krug() {
}
}
First create a new project by clicking the "New Project" icon, see the picture:

Then enter the name "GeometrijskiOblici", set the location you want and click the "Finish" button, see the picture:

A new project has been created with a generated package "geometrijskioblici" containing the file GeometrijskiOblici.java with the class of the same name, which is the main class, see the picture:

To add the other two classes, "Kvadrat" and "Krug", right-click the package geometrijskioblici and then click "New Class" in the context menu, as shown in the following picture:

The main class is shown below:
package geometrijskioblici;
import java.util.Scanner;
public class GeometrijskiOblici {
public static void main(String[] args) {
Scanner ucitavac = new Scanner(System.in); //An object for reading data is created
Kvadrat kvadrat1 = new Kvadrat(); //The object of the first square is created
Kvadrat kvadrat2 = new Kvadrat(); //The object of the second square is created
Krug krug1 = new Krug(); //An object of the class Krug is created
/*Reading the data*/
System.out.println("Enter the sides of both squares and the radius of the circle, in this order");
kvadrat1.a = ucitavac.nextDouble(); //Calls the method of the object that returns the double value read
kvadrat2.a = ucitavac.nextDouble(); //Calls the method of the object that returns the double value read
krug1.r = ucitavac.nextDouble(); //Calls the method of the object that returns the double value read
/*Computing the areas of the square and circle objects*/
kvadrat1.P = kvadrat1.a * kvadrat1.a; //Computing the area of the 1st square
kvadrat2.P = kvadrat2.a * kvadrat2.a; //Computing the area of the 2nd square
krug1.P = krug1.r * krug1.r * Math.PI; //Computing the area of the circle
/*Printing the results*/
System.out.println("Area of the 1st square: " + kvadrat1.P);
System.out.println("Area of the 2nd square: " + kvadrat2.P);
System.out.println("Area of the circle: " + krug1.P);
}
}
Here we see that two objects, kvadrat1 and kvadrat2, were created from the same description (template), i.e. the class that describes them, Kvadrat. Notice that it is the same class for two different objects. The third object, krug1, was created using the class "Krug" as the description. When objects are created, the constructor of the class, which has the same name as the class, is called.
So to create objects of the class Kvadrat the constructor has that name too, and when creating an object of the class Krug the constructor is also called "Krug". It is a method that gives initial values to the attributes of objects at the moment they are created. More about it in the next lesson.
For reading, an object of the class Scanner is used, which must be imported:
import java.util.Scanner;
After reading, the areas of all 3 objects are computed and then the results are printed. The data that are attributes of individual objects are accessed through the references of those objects. E.g. to "get" the area of the second square, this must be done as follows:
kvadrat2.P
After starting the application and entering the data, the areas are printed, see the picture:
Program output:
Enter the sides of both squares and the radius of the circle, in this order
10
20
10
Area of the 1st square: 100.0
Area of the 2nd square: 400.0
Area of the circle: 314.1592653589793
Related articles
Check your knowledge
Open the quiz
Quiz: Classes and objects
1. What is a class?
2. What does new Kvadrat(5) do?
3. What does private in front of an attribute mean?
4. What is a static attribute?
CLASSES AND OBJECTS IN JAVA
Now that you have a basic understanding of the core principles behind Object-Oriented Programming (OOP) in Java, it’s time to delve deeper into the building blocks that make OOP so powerful: classes and objects. These two concepts are fundamental to creating structured and reusable code in Java.A class is essentially a blueprint or template that defines the properties and behaviors of objects. In other words, a class describes what an object will look like and what it can do, but it doesn’t represent the actual object itself. On the other hand, an object is an instance of a class, an actual entity that you can manipulate in your program.
In this section, we will explore how classes and objects work in Java, looking at their structure, how to create them, and how they interact with each other. You’ll also learn about key concepts such as constructors and the process of initializing objects, which set the foundation for creating effective and maintainable Java programs.
By the end of this section, you will have the knowledge to design your own classes, instantiate objects, and understand how these components form the backbone of object-oriented software. Let's get started!
Memory Allocation and Object Creation
In Java, objects are created using the new keyword, which allocates memory for the object on the heap. The syntax is:
type_name data_name = new constructor (parameters_constructor);
For example, to create an object of the Scanner class for reading user input:Scanner reader = new Scanner(System.in);
Example of a Scanner Object java
Scanner reader = new Scanner(System.in);System.out.println("Enter a number:");
int number = reader.nextInt();
System.out.println("You entered: " + number);
In this example, the Scanner object reads an integer from the user input and displays it. This demonstrates both the state (user input) and the behavior (reading and displaying data).
Class methods Scanner
There are some methods in the Scanner class, for example:- nextInt () - this method takes from the standard input the data typed on the keyboard, converts it into an integer.
- nextDouble () - this method takes from the standard input the data typed on the keyboard, converts it into a real number.
- identity (acts as a whole)
- state (has properties that can change)
- Behavior (can do some things and some actions can be done on it)
Software objects have a state. The part of the memory occupied by the software object is used for variables that contain values.
Software objects have behavior. Part of the memory they occupy is spent on storing methods (programs) that allow the facility to "do something." The object does something when one of its methods is executed
Assuming that for an object, we take the initial dialog window from the displayed application
- The tiles in the image represent the bytes in the memory that the object occupies.
- This object has some atributes(variables defined in the class), the size of the Dialog(width * height), and the title, as well as some methods that control its behavior
- The software object consists of variables and methods
Classes and objects on the example of points in the plane:
Task: Create 3 objects representing three points in level A, B, C. Move point A to the new A1 position.§Point the coordinates of the points after the move. Data points are given in the picture.We note that all three objects belong to the same class because they have the same properties x and y.There will be 3 different expansions (objects) of the same class
The status of point A will change during the program, but not the properties.
To create objects, we first need to create a class that will describe them. Class we will call Tacka. In it we will list the common attributes x and y that will have all 3 objects.
Class Point
The complete code is shown below:
File:Point.java
packagepointsintheplane;
public classPoint {
// Attributes of the class
doublex;
doubley;
// Constructor
publicPoint() {
/* Empty constructor */
}
// Constructor with parameters
publicPoint(doublex, doubley) {
this.x = x;
this.y = y;
}
}
File:PointsInThePlane.java
packagepointsintheplane;
public classPointsInThePlane {
/**
* @param args the command line arguments
*/
public static voidmain(String[]args) {
// Define point A without initial coordinates
PointA = newPoint();
// Define and initialize point B
PointB = newPoint();
// Define and initialize point C
PointC = newPoint();
// Set coordinates for point A
A.x = 2;
A.y = 4;
// Set coordinates for point B
B.x = 5;
B.y = -2;
// Set coordinates for point C
C.x = -4;
C.y = 2;
// Move point A to a new position
A.x = 1;
A.y = 3;
// Print the coordinates of the points
System.out.println("Coordinates of point A are " + A.x + ", " + A.y);
System.out.println("Coordinates of point B are " + B.x + ", " + B.y);
System.out.println("Coordinates of point C are " + C.x + ", " + C.y);
}
}
Explanation
In this Java example, two classes are used to represent points in the plane. The first class, Point, defines the attributes x and y along with two constructors: a default constructor and a parameterized constructor.
The second class, PointsInThePlane, contains the main method which demonstrates the following:
- A point
Ais created and later moved to a new position by updating its coordinates. - Points
BandCare also created and initialized with specific coordinates. - The coordinates of each point are printed to the console using
System.out.println.
This example simulates the process of moving a point in the plane without a graphical component, focusing solely on the manipulation of object attributes and output of their values.
Example: Geometric Shapes
Task: Create objects, for two squares and one circle. enter the sides of the square and the radius of the circle and calculate their areas.Solution:Given that two objects that represent squares have the same properties: side a and surface P, we can say that they belong to the same class, the class that describes any square. We can name this class eg Square or Square_Description, and that "description" will apply to any square.
On the other hand, an object that represents a circle does not have the same properties as a square, therefore, it belongs to another class that we can call, for example, Circle or Description_Circle. There is also that "main" class, from which the program is started and which has the main method in it. Let that class be called the same as the project: GeometricShapes. Within this class, objects are created and the flow of the entire program is controlled. Classes are created as follows. The Square class has square attributes: a(the length of the sides of the square), P(area) and an empty constructor.
In the next lesson, we will talk about methods, as constituent parts of classes and class constructors: Methods and objectsThe Square class is shown below:
import java.util.Math;
public class Square
{
double a; //A square page as a field or class attribute
double P; //The area of a square as a field or class attribute
//Empty class constructor
public Square() {
}
import java.util.Math;
public class Circle
{
double r; //Circle radius as a field or class attribute
double P; //The area of a circle as a field or class attribute
//Empty class constructor
public Circle() {
}
package geometricshapes;
import java.util.Math;
import java.util.Scanner;
public classGeometricShapes
{
publicstaticvoidmain(String[] args)
{
Scanner scanner = newScanner(System.in); // An object is created to enter the data
Square square1 = newSquare(); // The object of the first square is created
Square square2 = newSquare(); // A second square object is created
Circle circle1 = newCircle(); // An object of class Circle is created
/* Data entry */
System.out.println("Enter both squares and the radius of the circle in the order given");
square1.a = scanner.nextDouble(); // Reads the side length of the first square
square2.a = scanner.nextDouble(); // Reads the side length of the second square
circle1.r = scanner.nextDouble(); // Reads the radius of the circle
/* Calculation of areas of square and circle objects */
square1.P = square1.a * square1.a; // Calculates the area of the 1st square
square2.P = square2.a * square2.a; // Calculates the area of the 2nd square
circle1.P = circle1.r * circle1.r * Math.PI; // Calculates the area of a circle
/* Print the results */
System.out.println("Area of the 1st square: " + square1.P);
System.out.println("Area of the 2nd square: " + square2.P);
System.out.println("Circle area: " + circle1.P);
}
}
So, for creating objects of the Square class, the constructor is called that, while when creating an object of the Circle class, the constructor is also called "Circle". It is a method that serves to give objects some initial values to their attributes at the time of creation. There will be no more talk about it in the next lesson.
For loading, the Scanner class object is used, which must be imported:
Method Overriding
Method overriding allows a subclass to provide its own implementation of a method that is already defined in its superclass. In Java, methods are virtual by default, so you do not need to use a keyword like virtual as in C++. When a method is overridden, calling it on a superclass reference that points to a subclass object will invoke the subclass’s version of the method.
public classBase {
public voiddisplay() {
System.out.println("Base class display"); // Print message from Base class
}
}
public classDerivedextendsBase {
public voiddisplay() {
System.out.println("Derived class display"); // Print message from Derived class
}
}
public classTest {
public static voidmain(String[] args) {
Baseobj = newDerived(); // Create a Derived object referenced by a Base variable
obj.display(); // Calls Derived.display() due to overriding
}
}
Explanation
In this Java example, the class Base defines a method display() that prints a message indicating that it belongs to the base class. The class Derived extends Base and overrides the display() method to provide its own implementation. Because Java methods are virtual by default, when we create a Base reference to a Derived object and call display(), the overridden method in Derived is executed.
This demonstrates polymorphism in Java, where the method call is dynamically resolved at runtime to the subclass's implementation.
Static Variables and Methods
In Java, static variables and methods belong to the class rather than to any individual object. This means that a static variable is shared by all instances of the class, and a static method can be called without creating an object. In contrast, non-static (instance) variables and methods belong to individual objects.
In the example below, we have a class that contains both a static variable and a regular instance variable. The static variable staticCounter is incremented every time any object calls the increment() method, whereas the instance variable objectCounter is unique for each object. Additionally, the static method displayStatic() shows the current value of the static variable without needing an object.
classPrimer {
static intstaticCounter = 0; // Shared among all instances
intobjectCounter = 0; // Unique to each object
voidincrement() {
objectCounter++; // Increases only for this object
staticCounter++; // Increases for all objects
}
voiddisplay() {
System.out.println("Object counter: " + objectCounter + ", Static counter: " + staticCounter);
}
static voiddisplayStatic() {
System.out.println("Static counter (from static method): " + staticCounter);
}
}
public classTest {
public static voidmain(String[] args) {
Primer obj1 = new Primer();
Primer obj2 = new Primer();
obj1.increment();
obj1.increment();
obj2.increment();
obj1.display(); // Shows values for obj1
obj2.display(); // Shows values for obj2
Primer.displayStatic(); // Calls static method using class name
}
}
Explanation of the Code
- Static Variable:
staticCounteris declared as a static integer, meaning it is shared among all objects of the classPrimer. Its value changes collectively for all instances. - Instance Variable:
objectCounteris a non-static variable, meaning each object has its own separate value. - Increment Method: The
increment()method increases both the object's instance counter and the shared static counter. - Display Methods: The
display()method prints both counters, while the static methoddisplayStatic()prints only the static counter and can be called without an object. - Usage in main(): Two objects (
obj1andobj2) are created. Their counters are updated separately, but the static counter remains shared. The static method is called via the class namePrimer.displayStatic().
Application of Static Variables and Methods, and Method Overriding in GeometricShape Example
In this extended example, we enhance the basic geometric shape classes by introducing static variables to count the number of objects created and by overriding the toString() method to provide a clear string representation of each object.
The static variables are shared among all instances of the class, while instance variables remain unique to each object.
package geometricshapes;
public classSquare {
doublea; // Side length of the square
doublearea; // Area of the square
static intcount = 0; // Static counter for Square objects
publicSquare(doublea) {
this.a = a;
this.area = a * a;
count++; // Increment static counter
}
@Override
public StringtoString() {
return "Square [side=" + a + ", area=" + area + "]";
}
}
package geometricshapes;
public classCircle {
doubler; // Radius of the circle
doublearea; // Area of the circle
static intcount = 0; // Static counter for Circle objects
publicCircle(doubler) {
this.r = r;
this.area = r * r * Math.PI;
count++; // Increment static counter
}
@Override
public StringtoString() {
return "Circle [radius=" + r + ", area=" + area + "]";
}
}
package geometricshapes;
importjava.util.Scanner;
public classGeometricShapes {
public static voidmain(String[] args) {
Scanner scanner = newScanner(System.in); // Create a Scanner object for input
Square square1 = newSquare(scanner.nextDouble());
Square square2 = newSquare(scanner.nextDouble());
Circle circle1 = newCircle(scanner.nextDouble());
System.out.println(square1);
System.out.println(square2);
System.out.println(circle1);
System.out.println("Total squares created: " + Square.count);
System.out.println("Total circles created: " + Circle.count);
scanner.close();
}
}
Explanation
- Static Variables: The static variable
countin each class (SquareandCircle) is shared among all instances of that class. Each time a new object is created, the constructor increments this counter. - Instance Variables: Instance variables (such as
ainSquareandrinCircle) are unique to each object. - toString Method: The
toString()method is overridden in both classes to provide a string representation of the object, displaying its dimensions and calculated area. - Usage in main(): In the
GeometricShapesclass, objects ofSquareandCircleare created and printed. The static counters show the total number of objects created for each shape.
| Previous |< Understanding Java as an Object-Oriented Language |
Next Objects and methods>| |







