简体   繁体   中英

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. The following would not be allowed, since method foo in ClassB must be 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. It is a completely different method, that only calls (explicitly or implicitly) the constructor of 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. If ClassA doesn't have one and you don't call another in ClassB's constructor, the compiler will be unhappy.

// 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. (This default constructor again will simply call super() , see above).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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