如果我没有明确说明方法或实例变量的默认访问修饰符是什么?
例如:
package flight.booking;
public class FlightLog
{
private SpecificFlight flight;
FlightLog(SpecificFlight flight)
{
this.flight = flight;
}
}
Run Code Online (Sandbox Code Playgroud)
此构造函数的访问修饰符是受保护的还是包的?同一个包中的其他类可以flight.booking
调用这个构造函数吗?
我们都知道,如果我们没有专门定义构造函数,编译器会插入一个不可见的零参数构造函数.我认为它的访问修饰符是公开的,但在处理内部类问题时,我发现也许我错了.这是我的代码:
public class Outer {
protected class ProtectedInner {
// adding a public constructor will solve the error in SubOuterInAnotherPackage class
//public ProtectedInner() {}
}
}
Run Code Online (Sandbox Code Playgroud)
并且Outer
在另一个包中有一个子类:
public class SubOuterInAnotherPackage extends Outer {
public static void main(String[] args) {
SubOuterInAnotherPackage.ProtectedInner protectedInner
= new SubOuterInAnotherPackage().new ProtectedInner(); // Error!! Can't access the default constructor
}
}
Run Code Online (Sandbox Code Playgroud)
您将在main()
方法中收到错误,但如果向ProtectedInner
类中添加公共构造函数,则会解决该错误.这就是为什么我认为默认构造函数的修饰符不公开!那么有谁能告诉我默认构造函数的访问修饰符是什么?
我在两个不同的包中有两个类.对于一个类,我已经定义了一个构造函数而没有为它设置访问修饰符.我想在另一个包中实例化该类的对象并获取错误' the constructor xxx() is not visible
'.
如果我定义访问修改为public
它是好的.我认为构造函数默认是公开的?
我有两个文件:
public interface PrintService {
void print(PrintDetails details);
class PrintDetails {
private String printTemplate;
}
public interface Task {
String ACTION = "print";
}
}
Run Code Online (Sandbox Code Playgroud)
和
public class A implements PrintService {
void print(PrintDetails details) {
System.out.println("printing: " + details);
}
String action = PrintService.Task.ACTION;
}
Run Code Online (Sandbox Code Playgroud)
我认为代码看起来没问题,但是我在第二个文件中收到错误信息void print(PrintDetails details) {
:
无法降低继承方法的可见性
PrintService
.
有人能解释这对我意味着什么吗?
我有这段代码,并生成错误,因为我已经添加到其类的构造函数中.
class NestedClass
{
class A
{
A() {}
}
class B
{
// no constructor
}
public static void run()
{
A a = new A(); // error
B b = new B(); // no error
}
}
Run Code Online (Sandbox Code Playgroud)
错误是:
NestedExample.A is inaccessible due to protection level
Run Code Online (Sandbox Code Playgroud)
请帮我解释一下.
谢谢 :)