Bohn
Bohn

Reputation: 25

abstract constructor java

How do i get the sub constructor from second and third? Since public abstract first doesnt work?

public abstract class First {

    public Point position;

    public First() {}  //how do i make this constructor like an abstract?
                      // so that it will go get Second constructor or Third
}

public class Second extends First {

    public Second (Point x) {
        position = x;
    }
}

public class Third extends First {

    public Third(Point x) {
        position = x;
    }
}

Upvotes: 2

Views: 13249

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

Java will not allow you to access the constructor of a concrete class derived from the abstract class from within the abstract class. You can however, call the super classes (abstract class) constructor from the concrete class.

public abstract class First{

    public Point position;

    public Plant(Point x) {
      this.position = x;
    }
}

public class Second extends First {

    public Second(Point x) {
        super(x);
    }
}

Upvotes: 3

SJuan76
SJuan76

Reputation: 24885

When creating a Second or Third object, the programmer must use one of the constructors defined for that class.

First constructor will be called implicitly, if you don't do it explicitly using super. No need to make it abstract, you can either leave it empty or just not define it (Java will assume the implicit default constructor which has no arguments and performs no actions).

Upvotes: 1

Related Questions