Lesson 26 of 34

Constructors and this

9 min 30 XP

A constructor is a special method with the class's name and no return type. It runs automatically on new. this.name means the object's field; plain name is the parameter.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Override toString() and System.out.println(object) prints something readable instead of Book@1b6d3586.

Challenge

+30 XP

Write class Employee with fields name and salary, a constructor Employee(String name, int salary) and a method int annualSalary() (salary × 12). In main(), read name and salary and print: Input: Ravi 25000 Output: Ravi earns 300000 per year

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.