Total Pageviews

Monday, September 03, 2012


CAN WE CALL A METHOD IN A CLASS WITHOUT AN OBJECT FROM MAIN FUNCTION WHICH IS DEFINED IN THE SAME CLASS???

Consider a class, say, class A, with one attribute and one method. main() is also inside the class A. Most of us may think since main() is in class A, we can access data members and methods without using an object. But this is not the case. You require an object to access the class members. 

Eg:


public class psvm
{
    int test=10;
    
    void display()
    {
        System.out.println("hai in display()");
    }
    
    public static void main(String args[])
    {
        System.out.println("hai");
        display();         //THIS WILL THROW AN ERROR!
    }
}

For the above program, you will get an error like...
non-static method display() cannot be referenced from a static context

But if the display method is declared static as
static void display()
then there will not be any error because static members does not require an object for invocation.

Also note keenly that the above program does not have import section but still the above program runs without any error. The reason is that the default package is 
java.lang.*

The reason why this package is made default is, coding a java program becomes useless without much functionality in java.lang because it is in this package, the basic data types like byte, string, int, thread etc are present. Hence this package is made as default.



4 comments:

  1. WOw wow wow :) :) :) :) great :) :) I was thinking wrong these days :D :D

    ReplyDelete
  2. cheeku @ even i was thinking wrong machi!!! i don't want others to do the same mistake... This blog is specially dedicated for our class CSE-B :)

    ReplyDelete
  3. awesome job..!!!very useful:)

    ReplyDelete