I have a doubt in the following code why we have to create the instance
of the same class like below
TestDelegateClass tdc = new TestDelegateClass();
in the given code.
My doubt is we have to create instance if there are two classes but here are having only one class
Please clarify me..
public delegate Boolean MyDelegate(Object sendingobj, Int32 x);public class TestDelegateClass{ Boolean MyFunction(Object sendingobj, Int32 x) { //Perform some processing return (true); } public static void main(String [] args) { //Instantiate the delegate passing the method to invoke in its constructor MyDelegate mdg = new MyDelegate(MyFunction); // Construct an instance of this class TestDelegateClass tdc = new TestDelegateClass(); // The following line will call MyFunction Boolean f = mdg(this, 1); }}
As I understand it, you're asking why you have to create an instance of the class when you already have one.
The answer is you don't already have an instance of the class. The static keyword modifying the main method allows the method to be called without instantiating the class. Static methods behave the same way no matter what class they're in. It's just a fancy way of organizing methods. Consider how the Math class has functions for Cos and Sin. You don't need to instantiate a new Math object in order to call these functions as they require no instance information to give you an appropriate result.
Hope that helps.
JRumana
ASKER
Ok... if i comment the line
// TestDelegateClass tdc = new TestDelegateClass();
then the above program will work or not? please clarify me.
The answer is you don't already have an instance of the class. The static keyword modifying the main method allows the method to be called without instantiating the class. Static methods behave the same way no matter what class they're in. It's just a fancy way of organizing methods. Consider how the Math class has functions for Cos and Sin. You don't need to instantiate a new Math object in order to call these functions as they require no instance information to give you an appropriate result.
Hope that helps.