Core Java

core26ConstructorsDemo

Path
pkg1core/core26ConstructorsDemo.java
Package
pkg1core
Study order
25
Run
Single-file source launch
Command
java pkg1core/core26ConstructorsDemo.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core26ConstructorsDemo.java
1package pkg1core;2 3/*4 * core26ConstructorsDemo.java5 * ---------------------------6 * Default, parameterized, and chained constructors; constructor overloading.7 *8 * EXPLANATION:9 *  - If you write no constructor, the compiler adds a no-arg default constructor.10 *  - Once you define any constructor, the default is NOT generated.11 *  - this(...) must be the first statement — chains to another constructor.12 *  - super(...) calls the parent constructor (must be first in subclass ctor).13 */14public class core26ConstructorsDemo {15 16    static class Employee {17        final String name;18        final int id;19        String department;20 21        Employee() {                          // default22            this("Unknown", 0);23        }24 25        Employee(String name, int id) {       // parameterized26            this(name, id, "General");27        }28 29        Employee(String name, int id, String department) {30            this.name = name;31            this.id = id;32            this.department = department;33        }34 35        @Override36        public String toString() {37            return name + " #" + id + " (" + department + ")";38        }39    }40 41    public static void main(String[] args) {42        System.out.println(new Employee());43        System.out.println(new Employee("Ravi", 101));44        System.out.println(new Employee("Maya", 102, "Engineering"));45    }46}