抽象类构造函数访问修饰符 [英] Abstract class constructor access modifier

查看:150
本文介绍了抽象类构造函数访问修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抽象类只能用作其他类扩展的基类,对吧?抽象类的构造函数可以具有通常的访问修饰符(public,protected和private(供内部使用))。 protected public 中的哪一个是要使用的正确访问修饰符,因为抽象类型似乎表明技术上是公共的构造函数会受到很大程度的保护吗?我应该在所有构造函数上使用protected吗?

An abstract class can only be used as a base class which is extended by some other class, right? The constructor(s) of an abstract class can have the usual access modifiers (public, protected, and private (for internal use)). Which of protected and public is the correct access modifier to use, since the abstract type seems to indicate that technically a public constructor will act very much protected? Should I just use protected on all my constructors?

推荐答案



抽象类型似乎表明技术上公共构造函数将受到很大程度的保护

since the abstract type seems to indicate that technically a public constructor will act very much protected

这是不正确的。抽象类不能通过调用它的构造函数直接实例化,但是,任何具体的实现都将继承抽象类的方法和可见性

This is not correct. An abstract class cannot be directly instatiated by calling its constructor, however, any concrete implementation will inherit the abstract class' methods and visibility

所以抽象类当然可以有公共构造函数。

So the abstract class can certainly have public constructors.

实际上,抽象类的构造函数只能从实现的构造函数中调用,所以没有它是公开的还是受保护的。例如:

Actually, the abstract class's constructor can only be called from the implementation's constructor, so there is no difference between it being public or protected. E.g.:

public class Scratch
{
    public static abstract class A
    {
        public A( int i ) {}
    }

    public static class B extends A
    {
        private B() { super(0); };
    }
}

这篇关于抽象类构造函数访问修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆