2

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;
    }
}
Bohn
  • 25
  • 1
  • 1
  • 3

2 Answers2

3

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);
    }
}
Bohn
  • 25
  • 1
  • 1
  • 3
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1

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).

Bohn
  • 25
  • 1
  • 1
  • 3
SJuan76
  • 24,532
  • 6
  • 47
  • 87
  • what if i want to make a new First(x,y); inside a method in the 'First class', would this be posible? – Bohn Nov 29 '12 at 10:29
  • If the `First` class is `abstract`, you can not create any instance of it (that is what means `abstract`). So you won't be able to do `new First()`, whatever the parameters are. If you define a non-default constructor (a constructor with parameters) and not define the default constructor (without parameters), you will have to explicitly call super(x, y) from the subclasses constructors. – SJuan76 Nov 29 '12 at 10:47