-2

Members of a class are private by deafult. The following code doesn't work.

#include<iostream.h>
class Test
{

int x;
};
void main()
{       Test test = new Test();
        test.x=10;

}

However the same code works in Java?

class Test { 
        int x=5;
}


public class MyClass{
public static void main(String args[]) {
        Test test = new Test();
        System.out.println(test.x);
  }
}

According to me it should not work.. since int x is private by deafult, it should not be available to MyClass.

2 Answers2

0

No visibility modifier does not indicate that the member is private. If members were private by default, why would the private keyword be allowed on members? That'd be rather redundant.

Instead, no visibility modifier on a member means that the field is package-private -- that is, only visible to other classes in the same package as the member.

Also, struct doesn't exist in Java. You might be getting confused with another language... The only place where members are public by default are interfaces (and maybe enums?), provided the containing interface/enum is also public.

awksp
  • 11,292
  • 4
  • 35
  • 44
0

I think the default modifier is package private. Thus you can use test.x in a class which is in the same package as class Test.

Chris Margonis
  • 885
  • 11
  • 16