简体   繁体   English

具体类中的受保护构造函数与抽象类中的公共构造函数

[英]protected constructor in concrete class vs public constructor in abstract class

This question is a following question of null source for FilterInputStream/FilterOutputStream 这个问题是FilterInputStream / FilterOutputStreamnull源的以下问题

This question may be a duplicated with protected vs public constructor for abstract class? 对于抽象类,这个问题可能与protected vs public构造函数重复了吗? Is there a difference? 有区别吗? (C#) (C#)

I found that FilterInputStream designed like this. 我发现FilterInputStream设计得像这样。

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
        // ...
    }
}

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. 因此, java.io包中的任何类都可以调用new FilterInputStream()而其他包中的类不能这样做。

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. 它只能被继承并且它的子代可以被实例化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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