简体   繁体   中英

Why does Java disallow subclasses which cannot access any constructors of its super class?

This question is mainly in reference to Luiggi's answer to this SO question: Why can you not inherit from a class whose constructor is private?

I understand that Java enforces that every subclass constructor must call one of its superclass's constructors. If all the superclass's constructors are private, this is obviously not possible. So, if a subclass theoretically could inherit from a superclass with private constructors, the result would be that you couldn't call a constructor on the subclass.

But what if I never intend to create an instance of the subclass anyway? For example, what if my subclass only adds static fields and methods, and I'm only interested in using the static fields and methods of the superclass? Then I don't need a constructor for the subclass.

what if my subclass only adds static fields and methods, and I'm only interested in using the static fields and methods of the superclass

In that case you don't need inheritance - use composition !

You should seal your class by declaring it as final . Then it is guaranteed that no sub-classes can be made

If only adding subclasses and can only create the parent class, the child "class" is really just a helper class without adding any functionality/responsibilites/etc. to the parent. In many respects, it's meaningless.

A subclass of this sort would not be a legitimate subclass. Even if all of its fields and methods were declared static, it would inherit all of the fields and methods of all of its superclasses, all the way back up to Object. And there are non-static methods in Object. So this subclass would have some set of non-static methods (and possibly fields) in its declaration.

This subclass could then be used as a type of a field, variable, type parameter or method argument (ie anywhere a type can be used). The compiler would have to keep track of the fact that this particular type could only be used in some restricted sense. (Imagine a method that returned a value of this subclass for example).

There are, I'm sure, many more gotcha's for this sort of thing.

So, bottom line, it would make writing a compiler really hard.

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