why you choose instance method over class method
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   kishanrao_aepuru
Posted On:   Tuesday, July 23, 2002 09:12 PM

why you choose instance method over class method

Re: why you choose instance method over class method

Posted By:   Simon_Ablett  
Posted On:   Wednesday, July 24, 2002 05:32 AM

Because a method declared as having class scope (i.e. which is static) has no concept of an instance of the class and so does not have access to the attributes (state) of that instance. If you have a class that contains only class scope methods and data then, in effect, you will only ever have a single instance of that class regardless of how you reference it. Consider the following.


class MyClass
{
public MyClass( int a, int b )
{
mA = a;
mB = b;
}

public void setA( int a )
{
mA = a;
}

public void setB( int b )
{
mB = b;
}

public int getA( )
{
return mA;
}

public int getB( )
{
return mB;
}

private int mA;
private int mB;
}

Each time I create an instance of this class it will have its own distinct state (i.e. values of a and b).

MyClass m1 = new MyClass(1, 2);
MyClass m2 = new MyClass(3, 4);
MyClass m3 = new MyClass(5, 6);

System.out.println("M1: a="+m1.getA()+" b="+m1.getB());
System.out.println("M2: a="+m2.getA()+" b="+m2.getB());
System.out.println("M3: a="+m3.getA()+" b="+m3.getB());

this will output.

M1: a=1 b=2
M2: a=3 b=4
M3: a=5 b=6

If the accessors had been static then we could not have
set a and b because the compiler would not have known
which instance those attributes belonged in. If we had
made a and b static as well then the class could only
ever have had a single state which would have been 'shared'
amongst all instances. So each time we called the static mutators (setA and setB) we would have overwritten the existing values of the static attributes. The output of the previous example would therefore be.


M1: a=5 b=6
M2: a=5 b=6
M3: a=5 b=6

Hope that this clarifies things.

Regards.
About | Sitemap | Contact