abstract constructor java

13,101

Solution 1

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

Solution 2

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

Share:
13,101
Bohn
Author by

Bohn

Updated on June 04, 2022

Comments

  • Bohn
    Bohn almost 2 years

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