CAN I HAVE THE CLASS CONTAINING MAIN FUNCTION ANYWHERE IN THE PROGRAM?
It is not mandatory that a class which has main() must be at last. It can be anywhere. The program given below is an example...
EG:
public class psvm_class
{
static void print()
{
System.out.println("hai in print()");
}
public static void main(String args[])
{
System.out.println("hai in main()");
print(); //STATIC MEMBER OF SAME CLASS
//display(); THIS WILL THROW AN ERROR
demo.display(); //STATIC MEMBER OF DIFFERENT CLASS
System.out.println("a is "+demo.a);
}
}
class demo
{
static int a=0;
static void display()
{
System.out.println("hai in demo class");
}
}
OUTPUT
hai in main()
hai in print()
hai in demo class
a is 0
CAN I CALL STATIC MEMBERS JUST BY ITS NAME IF IT IS NOT PRESENT IN CURRENT CLASS???
It is well known that static members doesn't need any object for accessing it. If static members are present in the class from where it is called, then we can simply use its name for accessing it. But if it is in different class, we can't simply use its name. In this case, it is necessary to use the class name to specify that the static member which we are calling is in the class mentioned while calling. In the above example class demo has a static data member 'a' and static method display(). When they are accessed in main() without class name, an error is thrown like...
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: display at extend_psvm_class.main(extend_psvm_class.java:12)
Hence the correct way of accessing is
demo.a
demo.display()
But the static members of the class psvm_class can be called just by their name as
print()
A question may arise like why class name is used for accessing static members in different classes. This is because it is possible to have another class with static display() say...
class demo1
{
static void display()
{
System.out.println("hai in demo1");
}
}
Now in this case, if we simply use
display()
then compiler doesn't know which display() method to call. To avoid this ambiguity, whenever static members of different classes are accessed, they are done by their corresponding class name.
Very good thing :) :) Demo.disp is fine . I understood . Is it similar to obj of demo class ?? :)
ReplyDeleteno its not an object machi. it is the class name. It is used to specify that display() method which is called is in the class named "demo".
ReplyDelete