Accessors and Mutators


Premium Content - Free Preview

You saw how to edit a method that returned the ID of a student. In Object-Oriented programming, you usually want to make an Object's variables private which will prevent external code from directly accessing them. Instead, other code should use public methods of your Object for getting and modifying variable values. These methods are commonly called Accessors and Mutators.

Accessors

Accessor methods simply return the value of one of the Object's variables. For example, getStudentID() returned the Student's ID, so it's an accessor. To get the ID of student1 in other code, you would type student1.getStudentID().

Question: Why couldn't I just make the student's ID (SID) public, which would let me type student1.SID to get the ID?

Answer: That would work but it would violate the principle of Encapsulation, and would be much less flexible. For example, let's say you want to always return additional information with the ID. With an accessor, you were able to modify the method easily so any code that accessed the ID will receive the extra information. (If you directly accessed the variables, you would need to edit your code everywhere the variable is accessed.)
You could also run additional checks in the accessor, such as checking that there is a Student ID in the first place.

Mutators

Mutators are methods that change the value of an Object's variables. They can do this by directly changing the value of a variable. For example, in a Car class, you could have a method to set the speed:


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

Comments

  • your missing input values here i guess

  • @calo, in this challenge, there is no input.

  • Arent we missing here an input for the options ?

  • yup my bad ..that was before I had the answer right

  • the input values are at the top:
    Car c = new Car("green");
    System.out.println( c.getColor() );
    c.accelerate(5);
    System.out.println( c.getSpeed());

    cont...
  • anybody know the answer. please post

  • please post answers no comprendo

  • Jack, I will add a hint to help out. You only need to ask for help once! Also, please update your email info. Thanks.

  • oh thank you I had something capitalized that shouldn't have been

  • I have no idea what to do here? Please help me!

  • i figured it out, unbelievable i would never of guessed!

    public void accelerate(int amount)
    {
    if (speed+amount<=0 || speed+amount>=140){

    cont...
  • it is very hard to see the 'big picture'

Contact Us
Sign in or email us at [email protected]