抽象类可以有构造函数吗? [英] Can an abstract class have a constructor?

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

问题描述

抽象类可以有构造函数吗?

Can an abstract class have a constructor?

如果是这样,如何使用它以及用于什么目的?

If so, how can it be used and for what purposes?

推荐答案

是的,抽象类可以有构造函数.考虑一下:

Yes, an abstract class can have a constructor. Consider this:

abstract class Product { 
    int multiplyBy;
    public Product( int multiplyBy ) {
        this.multiplyBy = multiplyBy;
    }

    public int mutiply(int val) {
       return multiplyBy * val;
    }
}

class TimesTwo extends Product {
    public TimesTwo() {
        super(2);
    }
}

class TimesWhat extends Product {
    public TimesWhat(int what) {
        super(what);
    }
}

超类 Product 是抽象的并且有一个构造函数.具体类 TimesTwo 有一个只硬编码值 2 的构造函数.具体类 TimesWhat 有一个构造函数,允许调用者指定值.

The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.

抽象构造函数将经常用于强制类约束或不变量,例如设置类所需的最少字段.

Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.

注意:由于父级中没有默认(或无参数)构造函数抽象类,子类中使用的构造函数必须显式调用父构造函数.

NOTE: As there is no default (or no-arg) constructor in the parent abstract class, the constructor used in subclass must explicitly call the parent constructor.

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

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