Classes and objects in Java

Lesson 9 of 16 · 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

Software objects: the Dialog-Frame example

The next picture shows this object in memory

Classes and objects – the structure of an object

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.Classes and objects – example: points in the plane



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

Classes and objects – points in the plane, main class 3

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

Classes and objects – points in the plane, main class 4

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;
}
Figure 9: Classes and objects – points in the plane, main class 6

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.

Figure 10: Classes and objects – points in the plane, main class. Showing the data

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:

 Creating a new project in Java
Figure 11: Creating a new project in Java

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

Creating a new project in Java, entering the project name and location
Figure 12: Creating a new project in Java, entering the project name and location

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:

 Creating a new project in Java, the end
Figure 13: Creating a new project in Java, the end

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:

Adding new classes in Java, in NetBeans IDE
Figure 14: Adding new classes in Java, in NetBeans IDE

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
Figure 15: The GeometrijskiOblici application, created in Java, running

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?