Using static/class methods, this, and overloading

bullet

Static or class methods are available to all objects created from a class.  In that sense, they are global

bullet

They are referenced as classname.method rather than objectname.method

bullet

Static/class methods -

bullet

can be invoked without instantiating an object

bullet

can access class member variables

bullet

cannot access instance member variables

bullet

cannot use this

bullet

Example --

public class Gizmo
{
    private static final String manufacturer = "Gizmo Inc.";
    ...
    public static String getManufacturer()
    {
        return manufacturer;
    }
    ...
    // to use this ->
    MessageBox.show("Made by "+Gizmo.getManufacturer());
    ...
}

bulletOverloading - Having 2 or more methods with the same name; they differ by the type and number of parameters -- Unique parameter lists are the key

public class TV
{
    public void setAspectRatio(int width, int height)
    { ...
    }

    public void setAspectRatio(double ratio)
    { ...
    }

    public void setAspectRatio()
    { ...
    }
}

bulletUse --

private TV tv;
...
tv.setAspectRatio(100,75);
// or
tv.setAspectRatio(7.0/3.0);

bulletthis is a reference that always refers to the current object; same as in C++, but with "." instead of "->"
bulletIt is used primarily to eliminate ambiguity
bulletIt is also used to eliminate passing the current object as a parameter when another object of the same type is passed to a method
bulletExample --

public class Gizmo    // a class definition
{
private int length;    // member variables of the class
private int width;
private int depth;

public Gizmo(int length, int width, int depth)  //a constructor
{
this.length = length;    // initialize the member variables
this.width = width;      // with values from passed
this.height = height;    // parameters of the same name
}
}

wpe2.jpg (19970 bytes)

Download aspectRatio source code - pay particular attention to the code behind the Movie, Square, and TV buttons

Last updated by DrB on Wednesday, February 18, 2009