English

Consider the following code statement: public class Person { int age; public Person (int age) { this.age = age; } } Which of the following statements are valid for the given code? - Computer Science (Theory)

Advertisements
Advertisements

Question

Consider the following code statement:

public class Person
{ int age;
  public Person (int age)
   {
    this.age = age;
   }
}

Which of the following statements are valid for the given code?

  1. The keyword this in the constructor refers to the current instance of the class.
  2. The keyword this differentiates between the instance variable age and the parameter age.
  3. The keyword this can be used only in constructors.

Options

  • Only I and II

  • Only II and III

  • Only I and III

  • Only III

MCQ
Advertisements

Solution

Only I and II

Explanation:

The keyword in Java refers to the current instance of the class. The instance variable and constructor parameter share the same name (age). This keyword is not just for constructors. It can be used in instance methods, method chaining, and to return the current object.

shaalaa.com
  Is there an error in this question or solution?
2024-2025 (March) Official Board
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×