var in Java 11 bypass the protected access restriction
The behavior of var in Java, introduced in Java 10, does not bypass the protected access restriction in any special way. Instead, the misunderstanding often arises from how var is interpreted and its interactions with visibility rules in Java.
Let’s break it down:
How var Works
- Type Inference:
varis a shorthand for declaring local variables with their types inferred by the compiler at compile time.The type of the variable is determined from the initializer expression.
var str = "Hello, World!";// Equivalent toString str = "Hello, World!"; - Scope:
varcan only be used for local variables within methods, constructors, or initialization blocks.- It cannot be used for instance variables, method parameters, or return types.
The Protected Access Modifier
- Rules:
protectedmembers in Java are accessible:- Within the same package.
- In subclasses of the class where the member is declared (even if the subclass is in a different package).
- The access in subclasses can occur only via inheritance (e.g., calling the
protectedmember directly onthisor a subclass instance).
- Why This Restriction Exists:
protectedrestricts access to ensure encapsulation while allowing controlled inheritance-based access.
Misinterpretation of var and protected
Scenario Leading to Confusion
Consider the following example:
package com.example.base;
public class Parent {
protected String protectedField = "Protected Value";
}
package com.example.child;
import com.example.base.Parent;
public class Child extends Parent {
public void accessProtected() {
var value = this.protectedField; // Works
System.out.println(value);
}
}
Explanation
- Why Does This Work?
protectedFieldisprotectedand accessible inChildbecauseChildinherits fromParent.- The
varkeyword simply infers the type ofprotectedFieldasStringduring compilation. This inference does not bypass theprotectedaccess rules.
- Does
varChange Access Rules?- No,
vardoes not bypass access rules. If the access toprotectedFieldis invalid (e.g., from a non-subclass or unrelated class), it would result in a compilation error.
- No,
Scenario Where Access Fails
package com.example.unrelated;
import com.example.base.Parent;
public class Unrelated {
public void accessProtected() {
Parent parent = new Parent();
var value = parent.protectedField; // Compilation error!
}
}
Why Does This Fail?
protectedFieldis not accessible becauseUnrelatedis neither in the same package asParentnor a subclass ofParent.
Key Takeaways
vardoes not bypassprotectedor any other access restrictions. It merely infers the type of a variable at compile time.- Any perceived bypass is likely due to misunderstanding the rules of
protectedor the fact thatvarallows concise syntax that might make access appear different. - The rules for
protectedremain consistent regardless of whethervaris used or explicit types are declared.
No images available.