CodeGym /Courses /Java Syntax /Object interaction

Object interaction

Java Syntax
Level 2 , Lesson 1
Available

"Hi, Amigo. Today I'll tell you about a typical Java program. The big news is that every program written in Java consists of classes and objects."

"I already know what classes are. What are objects?"

"Let's start with an analogy. Suppose you want to build a small ship. You work on a design and then send the blueprint to a factory, where a ship will be assembled according to your design. Or a dozen ships, or as many ships as you want. My point is that dozens of identical ships can be made based on one blueprint."

"That's exactly how it works with Java."

"Java programmers are like design engineers, except instead of creating blueprints, they write classes. Ship parts are made based on blueprints, while objects are created based on classes."

"First, we write classes (make blueprints). Then, when the program is run, the Java machine creates objects based on these classes. It's exactly like how ships are built from a blueprint. One blueprint – many ships. The ships are different. They have different names and carry different cargo. But they are still similar. They all have an identical design, and are able to perform similar tasks."

"OK, I get your ship analogy. Could you give me a couple more to help me be sure I understand what you're saying?"

"Take, for example, bees..."

"No, scratch that. I've had a bad experience with bees. Let's take ants."

"An ant colony is a good example of how objects interact. Any ant colony consists of three classes: the queen, soldiers, and worker ants. The number of ants in each class varies. Usually a colony only has one queen, dozens of soldiers, and hundreds of workers. Three classes, hundreds of objects. The ants follow strict rules as they interact with ants in their own class and ants that belong to other classes."

"This is the perfect example. A typical program works exactly like that. There is a main object that creates objects in all the classes. The objects interact with each other and with the external world. The objects' behavior is hardwired (programmed) internally."

"I don't quite get it. I mean, I don't get it at all."

"These two explanations are two sides of the same coin. The truth is somewhere in between. The first example (about blueprints and ships) shows us the connection between a class and its objects. It's a powerful analogy. The ant colony analogy demonstrates the relationship between objects, which are described by classes and exist only while a program is running."

"You mean we need to write classes for all objects used in a program, and then describe their interactions?"

"Yes, but it's easier than it sounds. In Java, while a program is running, all entities are objects. Writing a program amounts to describing the various ways that objects can interact. The objects simply call each other's methods and pass the required data to them."

"It's a little fuzzy, but I think I almost get it."

"How do we know which methods to call and which data to pass?"

"Each class has a declaration, which indicates its intended use. Similarly, every method has a declaration that indicates what it can do and what data we need to pass to it. To use a class, you need to have a general understanding of what it does. You need to know exactly what each method does, but not exactly how it does it. It's like a magic wand."

"Huh! Sounds nice."

"Here. Have a look at the code of a class that copies files:"

Copy c:\data.txt to c:\result.txt
package com.codegym.lesson2;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy
{
    public static void main(String[] args) throws IOException
    {
        FileInputStream fileInputStream = new FileInputStream("c:\data.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("c:\result.txt");

        while (fileInputStream.available() > 0)
        {
            int data = fileInputStream.read();
            fileOutputStream.write(data);
        }

        fileInputStream.close();
        fileOutputStream.close();
    }
}

"I can't say I get it all, but I think I got the essence of it."

"Great. See you next time then."

"I almost forgot. Here's your task from Diego."

Comments (347)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Anonymous #11672331 Level 9, Columbus, United States
4 October 2025
what's happening
Илья Корнилов Level 11, Moscow, Russia
4 January 2025
pity there's no dislikes for the tasks. how can one guess what is to be done here?
Naif Al-Jaaidi Level 9, Aden, Yemen
11 January 2024
We created objects by calling populate method, so why should I create objects again inside main method? What I did is like this inside for loop: for(){ workers[i].sendForFood(); } for(){ soldiers[i].sendIntoBattle(); } Is my way better?
Bright Iniabasi Level 9, Nigeria
15 April 2024
Lol. I also had a hard time figuring it out. You don't have to create objects of the Worker and Soldier classes again, since they're created in the populate method at each iteration. You need to create loops in the main method, and in those loops, assign references to the existing Worker and Soldier instances, and then use those references to call the sendForFood and sendIntoBattle methods. For example: for (int i = 0; i < workers.length; i++) { // A reference is assigned to each existing Worker instance in the workers array. // The array, "workers," is a static variable of the Queen class, so it is visible // in the main method, even though it was initialised in the populate method. Worker worker = workers[i]; worker.sendForFood(); } I hope you get it now.
Rather Be Coding Level 14, Detroit, United States
12 November 2023
I didn't realize there was other classes already. Whoops 😅
Lishon Level 3, Nottingham , United Kingdom
6 July 2023
I was completely lost on this one. I went to the help sections and some people were talking about loops, but we haven't done those yet. , Also, I ran the Results analysis and it came out with, if I'm not mistaken, the exact the thing the requirements said not to. Maybe my understanding isn't that good.
piero lucchesi Level 2, Italy
10 May 2023
anche io voglio le lezioni in Italiano...c'è un modo, come si fa? grazie
LarryOP Level 2, not to say, Italy
9 May 2023
Guys, I put the Italian language but is not working, how can I change the language?
Entute Level 6, Peru
17 April 2023
Yo si lo entendí, lo resolví a la primera :😁
Oswaldo Ramirez Level 3, Mexico
28 April 2023
pasa resolucion pto
NightroWave Level 3, San Francisco, Norway
15 March 2023
El desarrollo de este ejercicio no se ha explicado en ningún punto (no al menos de manera específica). Deberían dedicar en el nivel 1 un apartado con ejercicios básicos para trabajar en diferentes métodos. Los hay, pero son muy básicos y apenas tienen prácticas enfocadas. Los que somos nuevos, en ejercicios como estos, no tenemos ni idea si no es consultando ayudas o tirando de las respuestas.
Fadhil Radhian Level 18, Semarang, Indonesia
12 March 2023
A suggestion : Codegym need to move this to the beginning levels, since you mentioned about objects there without ever explaining what they are. It can confuse newbies to programming. By the way, this platform rocks !