Bird
0
0

Given a class Employee with a constructor that takes String name and double salary, how do you create an object and immediately print its salary?

hard📝 Application Q9 of 15
Java - Classes and Objects
Given a class Employee with a constructor that takes String name and double salary, how do you create an object and immediately print its salary?
AEmployee e = new Employee("John", 5000); System.out.println(e);
BSystem.out.println(Employee("John", 5000).salary);
CSystem.out.println(new Employee("John", 5000).salary);
DEmployee e = Employee("John", 5000); System.out.println(e.salary);
Step-by-Step Solution
Solution:
  1. Step 1: Understand object creation and field access

    You can create an object inline with new Employee(...) and access its fields immediately.
  2. Step 2: Check each option for syntax correctness

    System.out.println(new Employee("John", 5000).salary); correctly creates an object and accesses salary. Employee e = new Employee("John", 5000); System.out.println(e); prints the object reference, not salary. System.out.println(Employee("John", 5000).salary); misses new keyword. Employee e = Employee("John", 5000); System.out.println(e.salary); misses new keyword.
  3. Final Answer:

    System.out.println(new Employee("John", 5000).salary); -> Option C
  4. Quick Check:

    Use new keyword and access fields directly for inline print [OK]
Quick Trick: Use 'new ClassName(...)' to create and access fields inline [OK]
Common Mistakes:
  • Omitting new keyword when creating object
  • Printing object reference instead of field
  • Incorrect syntax for constructor call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes