Jump to content

What is the difference between private and private static


newcoder1010

Recommended Posts

Hello,

I am not understanding the difference between private and private static. 

 


public class PrivateStatic {
	
   
    private static int x =2;
    private int y=6;

    public PrivateStatic (int newX, int newY){
        x = newX;
        y = newY;
    }

    public PrivateStatic (){
    }

    public void print(){
        System.out.println(x);
        System.out.println(y);
    }

    public static void main(String[] args){
    	PrivateStatic obj = new PrivateStatic(14,56);
    	obj.print();
    }
    
}

Output:

14

56

I see the behaviors are same from this above example. It is printing the new values for both. Can you please clarify the difference?

Thanks!

Link to comment
Share on other sites

I think the difference will become apparent once multiple instances are created. Try it out and see what happens.

public class PrivateStatic {

    private static int x =2;
    private int y=6;

    public PrivateStatic (int newX, int newY){
        x = newX;
        y = newY;
    }

    public PrivateStatic (){}

    public void print(){
        System.out.println(x);
        System.out.println(y);
        System.out.println("---");
    }

    public static void main(String[] args){
        PrivateStatic obj1 = new PrivateStatic(10,40);
        PrivateStatic obj2 = new PrivateStatic(11,41);
        PrivateStatic obj3 = new PrivateStatic(12,42);
    	obj1.print();
    	obj2.print();
    	obj3.print();
    }
    
}

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...