Object-Oriented Programming 2023/24

Exercise 1


Welcome to the first exercise in Object-Oriented Programming. See the basic information on how exercises are organized on the Exercises web page.


Software

For programming in Java, we will use:

You may use other environment instead of Eclipse. In the next exercise, you will also try the basic tools for working with Java from the command prompt.

Make an empty Java project in Eclipse. If you work on a CPU computer, create your own folder in a folder to which you have write access, probably C:\work. Add the HelloWorld.java file to the project and compile it and run it. When creating the project, make sure that the Create module-info.java file option is unchecked. Also, remove the name introduced in the field marked as Package. Packages and modules are used as higher level units of code organization and they are of importance in larger programs.

^


Tasks

  1. Try the code of the game with ogers and knights from the lecture (use the final version, which is in the Game1 folder). In Eclipse, after unpacking the archive, it is sufficient to drag the files containing the implementation of the classes into the Java project you prepared for this. Try to change the number of ogres of different kinds in the initialization loops and follow how this affects the program output.
  2. Note the revenge() method call in the attack() method of the Knight class. The keyword this, which represents a reference to the current or, better to say, active object (whose method is currently being executed), occurs as a parameter there. Add printing the reference this (System.out.println(this)) to this method and note that in each ogre–knight pair clash the number being printed is different. Why?
  3. Create another class derived from the BadOgre class. Add your own revenge() method to it. Add the new ogre objects into the object array. Do the clash method and loop need to be adapted?
  4. Create another class derived from the Knight class. During an attack, this kind of knight takes away more energy from the ogre. Add some objects of this new kind of knights into the knight array. Do the clash method and loop need to be adapted now? Calculate how many different combinations of knights and ogres you resolve by this.
  5. (non-compulsory task) Change the way the energy is being taken away If you want to employ randomness, you can use the random() method of the Math class, which provides also a number of different mathematical functions. You call it like this:
    Math.random();
    Assign the result adjusted accordingly (and converted into an int) to your own variable.


Valentino Vranić
vranic at stuba.sk