Todo:

  • Kopier constructor der ein anderes objekt initalisiert mit den gleichen values.
  • Public / Private and aliasing

Classes are passed by reference into functions (as all complex object in Java).

Constructors

We have access to the this reference inside our class. It is just a normal reference to our class.

We don’t need to use it to access the variables of our class, but we can to prevent name overwriting:

public int x;
public int y;
 
public Point(int x, int y) {
	this.x = x; // This allows us to still access our this.x, without having to use a different variable name in our constructor parameters
}

The properties of our class are initialised to their default values: public int x will be set to 0.

Constructor Overloading

We can crate a function public ThisClass(...) which is a constructor. We can then call new ThisClass() to create a ThisClass object.

Copy Constructor

We can implement a constructor public Point(Point other) that copies the values of another object into this one.

Private Constructor

If our class only has static methods. We can then set the constructor to private, in order to prevent someone from initialising such an object.

Aliasing

Aliasing produces issues with private properties in a class.

We can pass a reference to the same object into two classes that set that reference to private. Then we can still change the underlying data, even though it’s protected.

Static methods

Static methods can’t use the this or access non-static class methods. This allows us to “group” methods under a name/class.

This is useful for methods for which we don’t want to initialise a whole object. They can also be used by other methods in the class.

Static attributes

A static attribute is also possible, for constants for example. It’s possible to access them without initialising a class, just like objects.

There is only a single one of these values in the entire code then. This means that all other users of MyStaticClass.var then get my new value.

This is useful for helper classes like Math.

Access Control

There are:

  • public
  • private: only accessible from within the object itself. Not shared across other instances of the object.
  • static no initialisation needed to access the method/property:
    • this means that static int will be shared across all instances of that object
      • This allows us to have unique incremented ids.
        static int counter = 0;
        int id;
         
        public Person() {
         	id = counter;
         	counter += 1;
        }
    • You should always set a public public static to also be final as otherwise it can be overwritten.
  • final: prevents the overwriting (like const)

Enums