简体   繁体   English

Java中的构造函数是否具有访问修饰符继承?

[英]Is there access modifier inheritance for constructors in Java?

When extending a class in Java, I can give methods that I override higher or equal access modifiers, but not lower ones. 在Java中扩展类时,我可以提供覆盖较高或相等访问修饰符的方法,但不能覆盖较低的访问修饰符。 The following would not be allowed, since method foo in ClassB must be public : 不允许以下内容,因为ClassB foo方法必须是public

public class ClassA {
    public void foo() {}
}
public class ClassB extends ClassA {
    @Override
    protected void foo() {}
}

It seems that this does not apply to constructors. 似乎这不适用于构造函数。 I can do the following: 我可以执行以下操作:

public class ClassA {
    public ClassA () {}
}
public class ClassB extends ClassA {
    protected ClassB() {}
}

Why is that so? 为什么会这样? Are there other rules that also apply to constructors but do not to methods? 还有其他规则也适用于构造函数但不适用于方法吗?

Because The constructor of ClassB does not override the constructor of ClassA. 因为ClassB的构造函数不会override ClassA的构造函数。 It is a completely different method, that only calls (explicitly or implicitly) the constructor of ClassA. 这是一种完全不同的方法,仅(显式或隐式)调用ClassA的构造函数。 So the visibility can be lowered, too. 因此,可见度也可以降低。

Another intesting point is, that the default constructor of ClassA would be called if you didn't call many constructor of ClassA yourself. 另一个证明点是,如果您自己没有调用很多ClassA构造函数,则将调用ClassA的默认构造函数。 If ClassA doesn't have one and you don't call another in ClassB's constructor, the compiler will be unhappy. 如果ClassA没有一个,并且您没有在ClassB的构造函数中调用另一个,则编译器将感到不满意。

// This WILL call super() implicitly, without you actually having to write it
protected ClassB() {}

I assume you already know that the default constructor will be added implicitly if you don't write ANY constructor for your class at all. 我假设您已经知道,如果您根本不为类编写ANY构造函数,则会隐式添加默认构造函数。 (This default constructor again will simply call super() , see above). (再次使用此默认构造函数,只需调用super() ,请参见上文)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM