Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call constructor in an abstract class

Is it possible to call a constructor in a abstract class?

I read that this constructor can be called through one of its non-abstract subclasses. But I don't understand that statement. Can anybody explain this with an example?

like image 987
Mansouritta Avatar asked Jan 11 '23 09:01

Mansouritta


2 Answers

You can define a constructor in an abstract class, but you can't construct that object. However, concrete sub-classes can (and must) call one of the constructors defined in the abstract parent class.

Consider the following code example:

public abstract class Test {

    // abstract class constructor
    public Test() {
        System.out.println("foo");
    }

    // concrete sub class
    public static class SubTest extends Test {    
      // no constructor defined, but implicitly calls no-arg constructor 
      // from parent class
    }

    public static void main(String[] args) throws Exception {
        Test foo = new Test(); // Not allowed (compiler error)
        SubTest bar = new SubTest(); // allowed, prints "foo"
    }
}
like image 176
Duncan Jones Avatar answered Jan 12 '23 22:01

Duncan Jones


You can't call an abstract class constructor with a class instance creation expression, i.e.

// Invalid
AbstractClass x = new AbstractClass(...);

However, in constructing an object you always go through the constructors of the whole inheritance hierarchy. So a constructor from a subclass can call the constructor of its abstract superclass using super(...). For example:

public class Abstract {
    protected Abstract(int x) {
    }
}

public class Concrete {
    public Concrete(int x, int y) {
        super(x); // Call the superclass constructor
    }
}

As constructors of abstract classes can only be called within subclass constructors (and by chaining one to another within the same class), I typically make them protected... making them public would serve no purpose.

The normal rules apply if you don't specify a super(...) or this(...) call in a concrete subclass constructor - it's equivalent to a super(); statement at the start of a constructor, calling a parameterless constructor in the superclass... so there'd have to be such a constructor.

like image 33
Jon Skeet Avatar answered Jan 12 '23 23:01

Jon Skeet