3

Why is a field with no modifier visible in a subclass?

My super class:

public class SuperClass {

String s = "superString";

    public void method(){
       System.out.println("Super");
    }
 }

My sub class:

public class Test extends SuperClass{

public static void main(String args[]){
    Test t = new Test();
    System.out.println(t.s);
  }
}

I get no error message from eclipse, the program prints out: superString...

But it shouldn't as no modifier fields are only visible in the class and the package but not in sub classes, or what have I misunderstood? Thanks

user3435407
  • 799
  • 2
  • 12
  • 28

2 Answers2

4

Having no modifier means that the scope of the field or method is "package only".

So your subclass must be in the same package as the superclass, for it to have access to the field in the superclass that has no modifier.

Erwin Bolwidt
  • 28,093
  • 15
  • 46
  • 70
4

When no modifier is present then default access is applied, think of default access as package access, a class with default access can be seen only by classes within the same package

Your class Test must be in the same package as your SuperClass that's why it's visible.

source: http://www.datadisk.co.uk/html_docs/java/access_control.htm

lxcky
  • 1,658
  • 2
  • 11
  • 25