Back to all lessons


Lesson 9

Globals and hermetization


public class Main {
    public static void main(String[] args) {
        Library.x = 20;
        Library.show();
        Library.change();
        Library.show();
    }
}
class Library {
    public static int x;
    public static void show() {
        System.out.println("x = " + x);
    }
    public static void change() {
        x++;
    }
}
        

public class Main {
    public static void main(String[] args) {
        Library.setX(20);
        Library.show();
        Library.change();
        Library.show();
    }
}
class Library {
    private static int x;
    public static void show() {
        System.out.println("x = " + x);
    }
    public static void change() {
        x++;
    }
    public static void setX(int x) {
        Library.x = x;
    }
} 
Task 0

What would happen, if we change "Library.x" to just "x"?

Task 1

Create a new method in new class, that prints something.

  1. Add counter: it increases every time you call method.
  2. You shouldn't be able to change counter outside the class.
  3. Add a method to check, how many times method has been called.
Task 2

Create piggy bank class. How it works?

  1. You can put a coin (it increases balance).
  2. You can crash piggy bank. You should print: "Now you have no piggy bank, but you gain $XYZ."
  3. Make sure, you can crash piggy bank just once. Otherwise write: "It's already broken"
  4. Make sure, you musn't put a coin to crashed piggy bank. Otherwise write: "It seems useless."

Create an usage example (i.e. in main method).

Task 3

Create a new class called Statistics.

The class should:

  1. Hold a state of an array (unaccessible outside the class)
  2. Have a method to generate random data in array
  3. Have a method to sort array (don't use Arrays.sort). The method should be called everytime you generate random data
  4. Have a method that calculates mean value
  5. Have a method that calculates median value
  6. Have a method that calculates mode
  7. Have a method that calculates variance
  8. Have a method that calculates standard deviation
  9. Have a method that prints params for linear regression equation in format: y=Ax+B
Task 4

Watch https://www.youtube.com/watch?v=SkP2VBzgpKA.

Create a program, that helps solving problems like the one present on video using recursion.