SA

Constructors__1_

Class Constructors

Definition

  • Constructors are special methods called during the creation of an object.

  • They share the same name as the class.

  • Constructors do not have a return type, not even void.

Characteristics

  • Multiple constructors can exist within a class; they must differ in parameters, which is known as having different signatures.

  • If no constructor is defined, a default constructor is automatically created by the compiler.

Types of Constructors

  • There can be only one parameterless default constructor.

  • Constructors are invoked when an object is created using the new keyword.

  • Primitive types are automatically initialized to default values upon creation.

Example in Code

public static void main(String[] args) {
    MyPoint p = new MyPoint();
    // Constructor is called
}

Using Constructors

Object Creation

  • When creating objects from classes, the appropriate constructor along with itsparameters should be utilized.

  • Example: A MyPoint constructor requires two parameters to be specified.


The Static Keyword

Definition and Access

  • Static members defined in a class can be accessed without creating an object instance of that class.

  • They occupy only one memory location and maintain just a single copy.

  • Changes made to static members in one part of the code will affect all other uses of that member.

Declaration

  • Static members are declared using the static keyword.


Static Methods

Example Class Definition

public class MyMath {
    public static double PI = 3.1416;
    public static double CalculateArea(double radius) {
        return PI * radius * radius;
    }
}

class Test {
    public static void main(String [] args) {
        double myradius = 4.3;
        System.out.println(MyMath.CalculateArea(myradius));
        // Function is called without using an object
    }
}

Application in a Game Context

  • In a game scenario, modeling alien races like Martians:

    • Martians may attack if there are at least 3 Martians.

    • A strategy must be established to enable each Martian to know the number of Martians around.