Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying just a setter on a set/getter

I'm using getters and setters for creating an instance of a class.

Is it possible to adjust the value being set without having to have a private variable, and do it on the type directly?

For example, if my class is:

public class Cat()
{
public String Age{get; set; }
}

and I want to instantiate it doing:

new Cat({Age: "3"});

Now, if I have a function called ConvertToHumanYears that I want to call before it is being stored, I would imagine something like this is the right way:

public class Cat()
{
public String Age{get; set{ value = ConvertToHumanYears(value); }
}

But the above (and many dirivatives of it) seem to return errors. Is it possible to do something similar without having to have an additional private variable I set and get?

like image 389
Steve Avatar asked Feb 27 '11 03:02

Steve


People also ask

Can we use setter without getter?

All of these methods are referred to as getters and setters, even when a backing variable is used. It is not possible to access any controller variables without a getter or setter.

How do you use setters and getters in two different classes?

To fix this, you need to pass a reference to the GetterAndSetter instance from class A to B . You can do this e.g. by passing it as a parameter to a method of B , or by creating a new instance of A in B and calling a method that provides an instance of GetterAndSetter .

What comes first setter or getter?

getter/setter pairs. first getters, then setters (or the other way around)

What is @getter annotation in Java?

The @Getter annotation is used to generate the default getter implementation for fields that are annotated with the annotation. This annotation can also be used at the class level in which Lombok will generate the getter methods for all fields. The default implementation is to return the field as it is.


1 Answers

You cannot use auto property for getter and have a definition for setter.

it's either

public class Cat()
{
   public String Age{get; set; }
}

or

public class Cat()
{
  private String _age;

    public String Age{
      get{
          return _age;
      }
      set{
           _age = ConvertToHumanYears(value); 
      }
    }
  }

}
like image 122
Bala R Avatar answered Oct 02 '22 14:10

Bala R