Java Super-class Constructors .

Java Super-class Constructors

  • A constructor can invoke a super-class constructor using the method call super().
  • You must support the super() method with appropriate arguments to select the desired super-class constructor.
  • The special call to super() must appear as the first statement in your delegating constructor.
  • Making super() call to a super-class constructors from other methods is illegal.
    Super-class Constructor example:
    class Person {
    
      private int age;
      private String name;
    
      public Person(int age, String name) {
        this.age = age;
        this.name = name;
      }
    
      @Override
      public String toString() {
        return ("My name is " + name
                + " and I am " + age + " years old.");
      }
    }
    
    class Doctor extends Person {
      private String specialty;
      Doctor(int age, String name, String specialty) {
      // This is a call to the Person constructor with two parameters  
        super(age, name);
        this.specialty = specialty;
      }
    
      @Override
      public String toString() {
        return super.toString() + " My profession is " + specialty;
      }
    }
    
    public class SuperDemo {
    
      public static void main(String args[]) {
        Person peter = new Person(45, "Peter");
        System.out.println(peter);
        Doctor fred = new Doctor(46, "Fred", "dermatologist");
        System.out.println(fred);
      }
    }
    The result of this is:
    My name is Peter and I am 45 years old.
    My name is Fred and I am 46 years old. My profession is dermatologist
    You can download this example here (needed tools can be found in the right menu on this page).
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.