Search code examples
inheritancepolymorphismsubclasssuperclass

Passing SuperClass constructor parameters to a SubClass?


Just beginning to start implementing Super and Sub classes to our projects but I'm having a bit of a problem creating the Subclass constructors to allow for different types of accounts but following the same rules as the Superclass.

Here is the constructor error I'm having.

https://i.sstatic.net/x7UUu.png

enter image description here


Solution

  • In your Account class you have specified a constructor that takes multiple arguments: firstName, lastName, accountNumber etc..

    In the constructor of the subclass you have to invoke the constructor of the super class -> super()

    A little example:

    class Person {
        public String name;
        /*constructor*/
        public Person(String name) {
            this.name = name;
        }
    }
    
    class Student extends Person {
        public String studentNumber;
        /*constructor*/
        public Student(String name, String studentNumber) {
            /* invoke super constructor. The parameters have to match the 
             * parameters specified in the constructor of Person
             */
            super(name);
            /* Now set the properties that only belongs to Student */
            this.studentNumber = studentNumber;
        }
    }