-3

I am new to Java, could you please tell me - "what is the purpose of the protected variable and method in Java".

Thanks in advance.
JP.

1 Answers1

1

Take a look at the docs
The following table shows the access to members permitted by each modifier.

Access Levels

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

So, protected elements in a Java application will be accessible form subclasses, class itself AND classes in the same package!, knowing this, you should use protected when some methods or attributes of one class needs to be shared around.

  • If you don't want any leaking of internal state, then declaring all your member variables private is the way to go.
  • If you don't really care that subclasses can access internal state, then protected is good enough.
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109