-3

Why is v.v accessible if MyTest is not a parent-class of Val?

public class MyTest 
{
    public static void main (String args [])
    {
        ValX v = new ValX ();
        System.out.println ("A: " + v.v);  // is working, why?
    }
}


public class ValX extends Val
{
}


public class Val 
{
    protected float v = 11;
}

EDIT

I learned about the visibility of proteced within the package. Thats the reason. thanks!

Is there a way I can make v only visible to parent-classes without moving it to another package?

chris01
  • 10,921
  • 9
  • 54
  • 93
  • 2
    Because MyTest is in the same package as ValX. Protected access also gives package access. – Erwin Bolwidt Jun 28 '18 at 09:02
  • 2
    The float *is* protected. Protected variables can be accessed by every Class in the same package and any subclass. See https://stackoverflow.com/questions/215497/in-java-difference-between-package-private-public-protected-and-private –  Jun 28 '18 at 09:02
  • more than one `?` won't make us think harder about your problem – azro Jun 28 '18 at 09:06

1 Answers1

2

In Java, visibility levels form a completely ordered chain of inclusion.

A private member can only be seen from within the current class.

A package-private member can only be seen from within the current package, which the current class is a part of.

A protected member can only be seen from subclasses or from the current package, thus covering everything that package-private can see.

And a public member can be seen from everywhere.

Since your class MyTest is in the same package as Val, the protected visibility grants access.

kumesana
  • 2,495
  • 1
  • 9
  • 10