Mathias Bader
Mathias Bader

Reputation: 3826

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?

Upvotes: 1

Views: 133

Answers (1)

Florian Schaetz
Florian Schaetz

Reputation: 10652

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).

Upvotes: 6

Related Questions