Re: how to use static methods




"gencko" <passageliu@xxxxxxxxx> wrote in message
news:1143120490.075042.96430@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
thanks a lot.

But i still got a little bit confused,so can u give me an example to
show the wrong usage of statics?i mean what will the codes be like if
we tried to call instance methods in static context ,there are piles of
'good' codes and short passages about statics in the textbooks that i
read,so i really wanna what the 'bad' codes are like

thank you very much for another time

Well it isn't so much bad, as impossible. The compiler won't let you do it
and it doesn't make any sense.

eg

class MyClass {

public void methA() {}

public static void main(String[] args) {

methA(); // illegal, you need an instance
// of MyClass to call an instance method

new MyClass().methA(); // legal, we have an instance.
}
}

on the other side of the coin it is legal to call a static method from an
instance, but it is bad practice, since it is misleading.

class MyClass {

public static void methB() {}

public static void main(String[] args) {

methB(); // legal, MyClass is implicit
MyClass.methB(); // explict version

MyClass inst = new MyClass();
inst.methB(); // legal, but bad. [1]
}
}

[1] This is legal because the compiler says, I know that 'inst' is an
instance of MyClass so I know how to call the static method. But it is
*bad* because it looks like you are calling an instance method, so is
misleading to the maintainer. Obviously it is also a waste of resources
instantiating the object, but the usual times people do this is when they
have the instance anyway.

--
Mike W


.



Relevant Pages

  • Re: Empty string
    ... public static void Main ... MyClass m = new MyClass; ... public string Foo ... public void Foo2(int n, ref string str) ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Why new ?
    ... > I have created a lib project in c# with some functions. ... Your method is an instance method - it acts on an *instance* of the ... public static void WriteRegKey(string subKey, string name, string ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: self in method name
    ... the equivalent in Java is this: ... public static void bar1() { ... for the class method and the instance method in Ruby. ...
    (comp.lang.ruby)
  • Re: How to escape Main?
    ... I have to apparently not only declare the class as an object of itself ... public static void main ... myClass startApp = new myClass; ...
    (comp.lang.java.programmer)
  • Re: Shadow Variables and Inheritance
    ... use an instance method. ... public int getMagicNumber { ... public static void int THE_QUESTION = 41; ...
    (comp.lang.java.programmer)