This question is a following question of null source for FilterInputStream/FilterOutputStream
This question may be a duplicated with protected vs public constructor for abstract class? Is there a difference? (C#)
I found that FilterInputStream designed like this.
public class FilterInputStream extends InputStream { // concrete
protected FilterInputStream(InputStream in) { // protected
// ...
}
}
My question is, is there any difference if the code were
public abstract class FilterInputStream extends InputStream { // abstract
public FilterInputStream(InputStream in) { // public
// ...
}
}
After all, an abstract class cannot be created directly – only via a derived instance. Consequently, it is only the derived classes for whom it makes sense to access the constructor in the first place. Hence, ReSharper recommends that you make the constructor protected .
Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed.
Yes, an Abstract Class can have a Constructor.
Yes, you can declare an abstract method protected. If you do so you can access it from the classes in the same package or from its subclasses.
The main difference is that The first class can be instanciated whereas the second class cannot be instanciated because it is abstract.
A protected constructor can be called by subclasses or by classes in the same package.
Therefore any class in the package java.io
can call new FilterInputStream()
whereas classes in other packages cannot do this.
Also the question is if there are possible other constructors in the class for the first case?
So from inheritance there is not real difference but for using the class from the same package.
Yes There is one main difference that in first code you can use
FilterInputStream fis =new FilterInputStream(in);
but in second code you cannot use
FilterInputStream fis =new FilterInputStream(in);
because abstract class could not have any object. it only be inherited & its child can be instantiated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With