Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why protected can be access in same Package without inheritance in java? [duplicate]

Tags:

java

protected

  Modifier        Class     Package   Subclass  World
  public          Y         Y         Y         Y
  protected       Y         Y         Y         N
  no modifier     Y         Y         N         N
  private         Y         N         N         N


  public class a {
  protected int x;
  }

  public class b {
        b() {
              a A=new a();
              A.x=9;//why we can access this field ?
        }
  }

please help my to know the specific work of protected in Java

like image 504
motaz99 Avatar asked Nov 09 '12 14:11

motaz99


People also ask

Can Protected be accessed in the same package?

Protected members can be accessed from the child class of the same package. Package members can be accessed from the child class of the same package. Public member can be accessed from non-child classes of the same package. Private members cannot be accessed from non-child classes of the same package.

Can a protected variable be accessible from class to class within the same package?

Protected Access Modifier - Protected Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class. The protected access modifier cannot be applied to class and interfaces.

Does protected members get inherited in Java?

A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in.

Can protected members be accessed by objects Java?

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.


1 Answers

Why? Because that's how the Java programming language was designed. There's not much more to it.

Something that is protected is accessible from

  • the class itself,
  • classes in the same package (doesn't matter if they are subclasses or not),
  • subclasses (doesn't matter if they are in the same package or not).

This is different from C++, but Java is not C++, so it doesn't necessarily work in the same way.

like image 145
Jesper Avatar answered Sep 19 '22 17:09

Jesper