一个抽象类有一个构造函数? [英] Can an abstract class have a constructor?

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

问题描述

一个抽象类可以有一个构造函数?

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);
    }
}

超类 code>是抽象的,并有一个构造函数。具体类 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.


注意:由于在父
抽象类中没有默认(或没有arg)构造函数,必须指定子类中使用的构造函数。 p>

NOTE: As there is no default (or no-arg) constructor in the parent abstract class the constructor used in subclasses must be specified.

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

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