Java - EncapsulationWhich of the following is the correct syntax for a setter method for a private int variable named age?Aprivate void setAge(int age) { age = this.age; }Bpublic int setAge() { return age; }Cpublic void setAge(int age) { this.age = age; }Dpublic int getAge(int age) { this.age = age; }Check Answer
Step-by-Step SolutionSolution:Step 1: Identify setter method structureA setter method is public, returns void, and takes a parameter to update the private variable.Step 2: Check the parameter assignmentThe method assigns the parameter value to the instance variable using this.age = age;.Final Answer:public void setAge(int age) { this.age = age; } -> Option CQuick Check:Setter syntax = public void setVar(Type var) { this.var = var; } [OK]Quick Trick: Setter methods are void and assign parameter to this.variable [OK]Common Mistakes:Using return type int for setterAssigning instance variable to parameter instead of reverseMaking setter private
Master "Encapsulation" in Java9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Java Quizzes Classes and Objects - Instance variables - Quiz 8hard Custom Exceptions - Why custom exceptions are needed - Quiz 4medium Exception Handling - Finally block - Quiz 7medium Exception Handling - Try–catch block - Quiz 12easy Exception Handling - Throw keyword - Quiz 11easy Inheritance - Inheritance limitations - Quiz 10hard Interfaces - Multiple inheritance using interfaces - Quiz 11easy Object-Oriented Programming Concepts - Classes and objects - Quiz 11easy Polymorphism - Runtime polymorphism - Quiz 12easy Polymorphism - Runtime polymorphism - Quiz 8hard