Prateek Kiran
Prateek Kiran

Reputation: 35

Data access by Static Methods

As texts say, Static methods don't access non-static data, so howcome main() method (declared as static) in nearly all programming languages, is able to work on instance members ?

Upvotes: 1

Views: 1483

Answers (5)

Oded
Oded

Reputation: 498932

The static Main method, at least in C# is used to create instances of classes used by the application - these instances are used to access their instance variables.

You will see in most applications calls to new in the Main method. This creates an instance of a class that can access instance variables.

Upvotes: 2

mo.
mo.

Reputation: 3534

The Main-Method is a static entry-point. In Java it mostly looks like this:

public class MainClass { 
    public static void main(String[] args){ 
        MainClass m = new MainClass();
        m.DoSomething();
        m.DoSomethingPrivate();

        DoSomethingStatic
    }

    public void DoSomething() {}
    private void DoSomethingPrivate() {}

    public static void DocSomethingStatic() {} 
}

It has only direct access to protected or private instance-members.

Upvotes: 1

Santosh
Santosh

Reputation: 17893

"Static methods don't access non-static data" More precisely : Static methods don't access non-static members.

Upvotes: 0

David B
David B

Reputation: 2698

A main method can't access the non-static fields in the class that holds main. If you provide it with an instance (or create a new instance within the method), it can access those fine. Similar to this:

public static void foo(String s) {
    System.out.println(s.toUpperCase());
}

Upvotes: 0

mprabhat
mprabhat

Reputation: 20323

That is not true as far as Java is concerned, you can only access instance variable after creating an instance of that Class within main.

The moment you create an instance of a class it become method local and not instance, and then you are accessing properties of that object, but inside main method you cannot directly use the instance variable.

for e.g.

public class TestStatic1 {
    private int number = 0;

    private static int staticnumber = 0;

    public static void main(String[] args) {
        number = 10; // cannot compile at this line.

        staticnumber = 10;
    }
}

Another one

public class TestStatic1 {
    private int number = 0;

    private static int staticnumber = 0;

    public static void main(String[] args) {
        TestStatic1 static1 = new TestStatic1();
        static1.number = 10; // perfectly fine, accessed via an object.

        staticnumber = 10;
    }
}

Upvotes: 4

Related Questions