posted 24 years ago
Hello,
you can invoke a static method by class name or instance name.
In this example there is an instance method and a static method
which do the same thing:
They compare circles by size. The instance method only needs
the comparison circle as parameter because the other circle is
being passed by reference (c1.bigger(c2));
The static method can also be invoked by reference (c1.bigger(c1,
c2) but it cannot acces the instance variables of the referenced
object (by "this") so it needs both circles beeing passed as
parameters.
--------------------------------------------------------------
class Circle {
public double x, y, r; //Instance Variables
Circle(int x, int y, int r) {this.x=x; this.y=y; this.r=r;} //Constructor
// Instance Method for comparing circles
// The instance method only needs one circle passed as the second circle
// is passed by reference and accessible by "this"
public Circle bigger(Circle c)
{
if (c.r > r) return c; else return this; // if (c.r > this.r) ...
// compiler inserts this.r automatically!
}
// Class Method for comparing circles
// The static method needs both circles as it cannot reference the
// instance variables by "this" like an istance method
public static Circle bigger(Circle a, Circle b)
{
if (a.r > b.r) return a; else return b;
}
public String toString() {return "Circle: x ="+x+"y= "+y+"r= "+r;}
}
public class Circletest {
public static void main (String args[])
{
Circle c1 = new Circle(2,3,2);
Circle c2 = new Circle(2,4,4);
// Invoke instance method
System.out.println(c1.bigger(c2));
// Invoke static method
System.out.println(Circle.bigger(c1, c2));
System.out.println(c1.bigger(c1, c2));
}
}