Common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most constructor mistakes fall into two groups. Some stop javac, and the message names the line. Others compile and quietly give wrong data, so only the output shows the problem: those are the ones to hunt for.
Mistakes and fixes at a glance
Most constructor errors name the line, but the words can mislead. A misspelt constructor name becomes a method without a return type, so javac talks about a "return type" when the real fix is the spelling.
Example 1 · A typo in the constructor name
class Student { String name;
Studnet(String name) { this.name = name; }}
public class TypoDemo { public static void main(String[] args) { Student s = new Student("Kavya"); System.out.println(s.name); }}TypoDemo.java:4: error: invalid method declaration; return type required
Studnet(String name) {
^
1 errorWhat this code does
Studnetis not the class name, so Java reads it as a method, and a method needs a return type.- The message talks about a "return type", but the real fix is the spelling:
Student.
Review: What is a constructor? (opens in a new tab). The other common mistakes, each with what goes wrong and the fix:
voidbefore the name →required: no argumentsatnew→ removevoid. Review: What is a constructor? (opens in a new tab)new X()after writing onlyX(String)→found: no arguments→ pass the value, or addX() { }. Review: The default constructor (opens in a new tab)- Arguments in the wrong order →
incompatible types→ follow the header. Review: Constructors with parameters (opens in a new tab) - Two constructors with the same parameter types →
already defined→ change one list. Review: Constructor overloading (opens in a new tab) - A line above
this(...), or constructors calling each other in a loop →call to this must be first statement in constructor/recursive constructor invocation→this(...)first, and end every chain at the full constructor. Review: Call one constructor from another with this() (opens in a new tab)
Bugs that compile
A ticket class compiles without a single warning, yet prints null, swapped cities and a negative fare. These silent bugs show only in the output, so read the constructor line by line against what it should do.
Example 2 · Three silent bugs in one class
class Ticket { String passenger; String from; String to; int fare;
Ticket(String passenger, String from, String to, int fare) { passenger = passenger; this.from = from; this.to = to; if (this.fare < 0) { throw new IllegalArgumentException("Bad fare"); } this.fare = fare; }}
public class SilentBugsDemo { public static void main(String[] args) { Ticket t = new Ticket("Priya", "Jaipur", "Delhi", -500); // Priya goes Delhi to Jaipur System.out.println(t.passenger + ": " + t.from + " to " + t.to + ", Rs. " + t.fare); }}null: Jaipur to Delhi, Rs. -500
What this code does
- Bug 1:
passenger = passenger;never sets the field. Bug 2: the check readsthis.fare, which is still0, so -500 passes. - Bug 3 is in
main:"Jaipur"and"Delhi"are swapped. All three compile without a warning.
Example 3 · The same class, built well
class Ticket { String passenger; String from; String to; int fare; String status = "Confirmed";
Ticket(String passenger, String from, String to) { this(passenger, from, to, 500); }
Ticket(String passenger, String from, String to, int fare) { if (fare < 0) { throw new IllegalArgumentException("Fare cannot be negative: " + fare); } this.passenger = passenger; this.from = from; this.to = to; this.fare = fare; }}
public class GoodTicketDemo { public static void main(String[] args) { Ticket t = new Ticket("Priya", "Delhi", "Jaipur"); System.out.println(t.passenger + ": " + t.from + " to " + t.to + ", Rs. " + t.fare + ", " + t.status); try { new Ticket("Rohan", "Pune", "Goa", -500); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } }}Priya: Delhi to Jaipur, Rs. 500, Confirmed Fare cannot be negative: -500
What this code does
- The full constructor checks the parameter and uses
this.for every field; the short one chains to it with a default fare. statusis the same for every new ticket, so it is a field initializer. A bad fare is refused, whichever constructor is used.
Review: The this keyword (opens in a new tab) for passenger = passenger;, and Constructors with parameters (opens in a new tab) for checking the parameter instead of the field and for swapped arguments.
Spot the bug
Each snippet below looks almost right. Read what it should do, tap the wrong line, then check the fix. Ask three questions: is it really a constructor, which variable does each name mean, and does every chain end?
Find the bug
Find the constructor bug
Select the line that is wrong.
This should create a Dell laptop.
Round 1 of 6Everything together: a trace
A class mixes a field initializer with a chain. Trace it the safe way: for each new, write the defaults, then the initializer, then each constructor body from the deepest one out.
Example 4 · Defaults, initializer, chain: a trace
class Order { String customer; int items = 1;
Order() { this("Guest"); System.out.println("Order(): " + customer + ", " + items); }
Order(String customer) { System.out.println("Order(String) starts: " + this.customer + ", " + items); this.customer = customer; items = items + 2; }}
public class OrderTraceDemo { public static void main(String[] args) { Order a = new Order(); Order b = new Order("Kavya"); System.out.println(a.customer + " " + a.items + ", " + b.customer + " " + b.items); }}Order(String) starts: null, 1 Order(): Guest, 3 Order(String) starts: null, 1 Guest 3, Kavya 3
What this code does
- For each object: the default (
customerisnull), then the field initializer (items = 1), then the body ofOrder(String). - Only
aruns the rest ofOrder(), after itsthis("Guest")line. Each object has its own fields.
Review: Call one constructor from another with this() (opens in a new tab) for the full order, and The default constructor (opens in a new tab) for field initializers.
Finish up
Mark complete & continue
Next: Must-do problems: Constructors