Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

protected constructor in concrete class vs public constructor in abstract class

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
        // ...
    }
}
like image 492
Jin Kwon Avatar asked Aug 27 '13 05:08

Jin Kwon


People also ask

Should abstract classes have protected constructors?

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 .

Can we have public constructor in abstract class?

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.

Can abstract classes have concrete constructors?

Yes, an Abstract Class can have a Constructor.

Can we use protected in abstract class?

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.


2 Answers

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.

like image 176
Uwe Plonus Avatar answered Sep 22 '22 03:09

Uwe Plonus


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.

like image 25
Pulah Nandha Avatar answered Sep 25 '22 03:09

Pulah Nandha