在Java中,”protected”不是应该只能被子类访问吗?

huangapple go评论70阅读模式
英文:

isn't protected supposed to be accessible only by subclasses in Java?

问题

我真的很惊讶,这段代码没有引发任何编译错误。

class A {
	protected int a;
}
 
class B {
	void b() {
		A a = new A();
		a.a = 4;
	}
}
英文:

I got really surprised that this code didn't get me any compile errors.

class A {
	protected int a;
}
 
class B {
	void b() {
		A a = new A();
		a.a = 4;
	}
}

答案1

得分: 1

不,protected对于同一包中的其他类是可见的。

要记住的是,访问修饰符的目的是为了避免向其他人提供过多信息。如果你在同一包中工作,那么你已经拥有这些信息,如果需要的话就可以使用它。

英文:

No, protected is visible to other classes in the same package.

The thing to remember is that access modifiers are meant to keep from bothering OTHERS with too much information. If you are working in the same package, then you’ve already got the information, use it if you want to.

答案2

得分: 1

在Java中,protected变量在同一包内以及通过继承在包外是可访问的。如果来自包外的任何其他类尝试访问这些变量,编译器将在编译时抛出错误。
您可以在以下链接中详细了解:
https://javagoal.com/access-modifiers-in-java/#12

英文:

In java protected variable is accessible within the package and outside the package but by use of inheritance. If any other class from outside the package, try to access these variables the compiler will throw an error at compilation time.
You can read it detail
https://javagoal.com/access-modifiers-in-java/#12

huangapple
  • 本文由 发表于 2020年8月4日 10:42:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63239509.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定