yra*_*lik 111 java access-modifiers
如果我没有明确说明方法或实例变量的默认访问修饰符是什么?
例如:
package flight.booking;
public class FlightLog
{
private SpecificFlight flight;
FlightLog(SpecificFlight flight)
{
this.flight = flight;
}
}
Run Code Online (Sandbox Code Playgroud)
此构造函数的访问修饰符是受保护的还是包的?同一个包中的其他类可以flight.booking调用这个构造函数吗?
Sur*_*tta 105
来自Java 文档
如果一个类没有修饰符(默认,也称为包私有),它只在自己的包中可见(包是相关类的命名组 - 您将在后面的课程中了解它们.)
在member level,您还可以使用public修饰符或no modifier(package-private),就像使用顶级类一样,具有相同的含义.
你可以在这里阅读全文(我最近写的):
http://codeinventions.blogspot.com/2014/09/default-access-modifier-in-java-or-no.html
Pra*_*eep 87
来自文档:
Access Levels
Modifier Class Package Subclass World
-----------------------------------------------------
public Y Y Y Y
protected Y Y Y N
(Default) Y Y N N
private Y N N N
Run Code Online (Sandbox Code Playgroud)
SKG*_*SKG 32
这取决于具体情况.
当它在一个类中时:
class example1 {
int a = 10; // This is package-private (visible within package)
void method1() // This is package-private as well.
{
-----
}
}
Run Code Online (Sandbox Code Playgroud)
当它在一个界面内时:
interface example2 {
int b = 10; // This is public and static.
void method2(); // This is public and abstract
}
Run Code Online (Sandbox Code Playgroud)
JTH*_*Cat 12
Here is a code sample which should pretty much sum this up for you... In addition to the below, showing how you can't access a default in another package there is one more thing.
Default is not accessible in a subclass if the class that subclasses it is in another package, but it is accessible if the subclass is in the same package.
package main;
public class ClassA {
private int privateVar;
public int publicVar;
int defaultVar;
}
package main;
public class ClassB {
public static void main(String[] args) {
ClassA a = new ClassA();
int v1 = a.publicVar; // Works
int v2 = a.defaultVar; // Works
int v3 = a.privateVar; // Doesn't work
}
}
package other;
public class ClassC {
public static void main(String[] args) {
ClassA a = new ClassA();
int v1 = a.publicVar; // Works
int v2 = a.defaultVar; // Doesn't work
int v3 = a.privateVar; // Doesn't work
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
194077 次 |
| 最近记录: |