abstract class constructors

The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a default constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.
NOTE: As there is no default (or no-arg) constructor in the parent abstract class the constructor used in subclasses must be specified.
Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.


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() {

public class TimesWhat extends Product {
	public TimesWhat(int what) {

	public static void main(String[] args) {
		TimesTwo t2 = new TimesTwo();
		int a = t2.mutiply(4);
		System.out.println("Times Two " + a);

		TimesWhat t3 = new TimesWhat(3);
		int b = t3.mutiply(4);
		System.out.println("Times what " + b);


Times Two 8
Times what 12

You may also like...