Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (6.5k points)
Can we instantiate static methods and variables?

1 Answer

0 votes
by (11.3k points)

It is possible to invoke static elements of a class through objects but it is not possible to create separate instances of those data members when the memory allocation of those elements is static. To simply put it, creating an object and invoking these elements does not create a copy of these elements. Refer to the following code to get an idea:

public class HelloWorld{

    static int a=1;

    public static int hello()

    {

        a=2;

        return a;

    }

     public static void main(String []args){

        HelloWorld abc = new HelloWorld();

        HelloWorld bc = new HelloWorld();

        System.out.println(abc.hello());

        System.out.println(abc.a);

        bc.a=bc.a+1;

        System.out.println(abc.a);

     }

}

/* Output:

2

2

3

*/

As we can see, changing the value of the supposedly instantiated static integer variable through objects 'abc' and 'bc' changes the value of integer 'a' universally and not just for its instance. I hope that example makes it clear enough. You can always try variations of these conditions to get a firmer grasp of OOP concepts in Java.

Browse Categories

...