How do getters and setters work? - java

I'm from the php world. Could you explain what getters and setters are and could give you some examples?

Tutorial is not really required for this. Read up on encapsulation
private String myField; //"private" means access to this is restricted to the class.
public String getMyField()
{
//include validation, logic, logging or whatever you like here
return this.myField;
}
public void setMyField(String value)
{
//include more logic
this.myField = value;
}

In Java getters and setters are completely ordinary functions. The only thing that makes them getters or setters is convention. A getter for foo is called getFoo and the setter is called setFoo. In the case of a boolean, the getter is called isFoo. They also must have a specific declaration as shown in this example of a getter and setter for 'name':
class Dummy
{
private String name;
public Dummy() {}
public Dummy(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface. Also, many tools and toolkits that use reflection to examine objects only accept objects that have getters and setters. JavaBeans for example must have getters and setters as well as some other requirements.

class Clock {
String time;
void setTime (String t) {
time = t;
}
String getTime() {
return time;
}
}
class ClockTestDrive {
public static void main (String [] args) {
Clock c = new Clock;
c.setTime("12345")
String tod = c.getTime();
System.out.println(time: " + tod);
}
}
When you run the program, program starts in mains,
object c is created
function setTime() is called by the object c
the variable time is set to the value passed by
function getTime() is called by object c
the time is returned
It will passe to tod and tod get printed out

You may also want to read "Why getter and setter methods are evil":
Though getter/setter methods are commonplace in Java, they are not particularly object oriented (OO). In fact, they can damage your code's maintainability. Moreover, the presence of numerous getter and setter methods is a red flag that the program isn't necessarily well designed from an OO perspective.
This article explains why you shouldn't use getters and setters (and when you can use them) and suggests a design methodology that will help you break out of the getter/setter mentality.

1. The best getters / setters are smart.
Here's a javascript example from mozilla:
var o = { a:0 } // `o` is now a basic object
Object.defineProperty(o, "b", {
get: function () {
return this.a + 1;
}
});
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.
2. Getters / setters in php
Example from sof
<?php
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
?>
citings:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
http://tweener.ivank.net/
Getter and Setter?

Here is an example to explain the most simple way of using getter and setter in java. One can do this in a more straightforward way but getter and setter have something special that is when using private member of parent class in child class in inheritance. You can make it possible through using getter and setter.
package stackoverflow;
public class StackoverFlow
{
private int x;
public int getX()
{
return x;
}
public int setX(int x)
{
return this.x = x;
}
public void showX()
{
System.out.println("value of x "+x);
}
public static void main(String[] args) {
StackoverFlow sto = new StackoverFlow();
sto.setX(10);
sto.getX();
sto.showX();
}
}

Related

How can I associate two objects in main in Java [duplicate]

I'm from the php world. Could you explain what getters and setters are and could give you some examples?
Tutorial is not really required for this. Read up on encapsulation
private String myField; //"private" means access to this is restricted to the class.
public String getMyField()
{
//include validation, logic, logging or whatever you like here
return this.myField;
}
public void setMyField(String value)
{
//include more logic
this.myField = value;
}
In Java getters and setters are completely ordinary functions. The only thing that makes them getters or setters is convention. A getter for foo is called getFoo and the setter is called setFoo. In the case of a boolean, the getter is called isFoo. They also must have a specific declaration as shown in this example of a getter and setter for 'name':
class Dummy
{
private String name;
public Dummy() {}
public Dummy(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
The reason for using getters and setters instead of making your members public is that it makes it possible to change the implementation without changing the interface. Also, many tools and toolkits that use reflection to examine objects only accept objects that have getters and setters. JavaBeans for example must have getters and setters as well as some other requirements.
class Clock {
String time;
void setTime (String t) {
time = t;
}
String getTime() {
return time;
}
}
class ClockTestDrive {
public static void main (String [] args) {
Clock c = new Clock;
c.setTime("12345")
String tod = c.getTime();
System.out.println(time: " + tod);
}
}
When you run the program, program starts in mains,
object c is created
function setTime() is called by the object c
the variable time is set to the value passed by
function getTime() is called by object c
the time is returned
It will passe to tod and tod get printed out
You may also want to read "Why getter and setter methods are evil":
Though getter/setter methods are commonplace in Java, they are not particularly object oriented (OO). In fact, they can damage your code's maintainability. Moreover, the presence of numerous getter and setter methods is a red flag that the program isn't necessarily well designed from an OO perspective.
This article explains why you shouldn't use getters and setters (and when you can use them) and suggests a design methodology that will help you break out of the getter/setter mentality.
1. The best getters / setters are smart.
Here's a javascript example from mozilla:
var o = { a:0 } // `o` is now a basic object
Object.defineProperty(o, "b", {
get: function () {
return this.a + 1;
}
});
console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)
I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.
2. Getters / setters in php
Example from sof
<?php
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
}
?>
citings:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
http://tweener.ivank.net/
Getter and Setter?
Here is an example to explain the most simple way of using getter and setter in java. One can do this in a more straightforward way but getter and setter have something special that is when using private member of parent class in child class in inheritance. You can make it possible through using getter and setter.
package stackoverflow;
public class StackoverFlow
{
private int x;
public int getX()
{
return x;
}
public int setX(int x)
{
return this.x = x;
}
public void showX()
{
System.out.println("value of x "+x);
}
public static void main(String[] args) {
StackoverFlow sto = new StackoverFlow();
sto.setX(10);
sto.getX();
sto.showX();
}
}

Setter methods, multiple with no parameters or single with value?

I'm working on a java based game with a friend and I've noticed he's taking an approach that concerns me, in terms of maintainability.
For a class representing a playable Character, instead of just creating 1 method which sets an object's property, he's creating separate methods which set the property to a specific value.
Which of these 2 options would be the best to follow going forward?
Option 1
public void runFast() {
this.character.speed = 5.0f
}
public void walk() {
this.character.speed = 2.0f
}
public void stop() {
this.character.speed = 0.0f;
}
Option 2
public void setSpeed(float speedTemp) {
this.character.speed = speedTemp;
}
Why not use an enum to set the speed - then you can still have
void setSpeed(Speed speed) {
this.character.speed = speed.getAmount();
}
with:
enum Speed {
FAST(5.0f), WALK(2.0f), STOP(0.0f);
private final float amount;
private Speed(flaot a) { this.amount = a; }
public float getAmount() {
return amount;
}
}
That way, you can quickly update the values, but still have a predefined amount. Its flexible and easy to maintain. You might want to save the enum instead of the float.
My Solution would be to use Enums instead,
it is cleaner and has more context and easily extensible if you have more to do with your speed maxHeartRate in the future.
public class Character {
private Speed speed;
public Speed getSpeed() {
return speed;
}
public void setSpeed(Speed speed) {
this.speed = speed;
}
};
public enum Speed {
STOP(0),
RUN(5.5),
WALK(2.5);
double value;
Speed(double value) {
this.value = value;
}
public double getValue() {
return value;
}
};
IMHO the best option would be to declare constants/enums, and use the option 2.
Example (constants) :
public static final float STOP = 0.0f;
public static final float WALK = 2.0f;
public static final float FAST = 5.0f;
setSpeed(STOP|WALK|FAST);
Example (enums) :
public enum Speed
{
FAST(5.5f),
STOP(0),
WALK(2.5f);
float value;
Speed(float pValue)
{
this.value = pValue;
}
public float getValue()
{
return this.value;
}
}
setSpeed(Speed.FAST);
It depends. For example
Are speeds limited to a few predefined values? In that case using an enum would be a good solution.
Is walking / running / stopping going have side effects other than just setting the speed? As a contrived example, starting to run might cause the character to drop an item it's holding, or stopping might cause the character to skid a little. In this case having separate methods might make sense.
Or maybe there are only a few predefined states, but depending on the environment running speed might be different.
What it comes down to is: Which way of conceptually modeling the properties of your character works best for your game logic / physics? Work this out and then base the interface of your classes on that. Don't get too hung up on the exact API early on, this sort of stuff is pretty easy to refactor.
getter and setters are useful when you want that your code is readble and for avoiding that public class fields can be used in the wrong way from another classes.
This example show how is important.
CLASS A:
public class ClassA{
// in the body class
private String fieldClass1;
//classic setter
public void setfieldClass1(String f1)
{
fieldClass1 = f1;
}
}
CLASS B:
public class ClassB{
// in the bodyclass
public String fieldClass2;
//classic setter
public void setfieldClass2(String f2)
{
setfieldClass2 = f2;
}
CLASS C:
public class ClassC{
//in the body of the class this method use class a and class b
public void calc()
{
ClassA aObject = new ClassA();
ClassB bObject = new ClassB();
ClassA.fieldClass1 = 5 + 5; // illegal expression for the compiler and costrain the developer to use setters
ClassB.fieldClass2 = 8 + 8; // legal expression
}
}
This mean that you must define a "modifiers logic" (protected, private, public) before make setters and getters. Define before the modifiers and after define the setters and getters.

Is there any way to access this.toString()'s value when calling another constructor?

For everyone who is talking about the fact that the object is in an "unitialized state", please refer to the answer to this question which shows that an object reference can be passed around, dereferenced, have methods invoked from it, and have fields accessed before a constructor terminates and all fields have been assigned (including final fields).
So here's the use case:
public class Entity {
private final String name;
public Entity() {
this(toString()); //Nope, Chuck Testa
}
public Entity(String name) {
this.name = name;
}
}
The compiler error is:
Cannot refer to an instance method while explicitly invoking a constructor.
Note that toString() has not been overriden and is the default call from Object.
I'm certainly interested in the philosophical/technical reasons behind this, so if anyone can explain that, that would be an awesome bonus. But I'm looking for a way to call toString() from that default constructor as it refers down to the more specific one with more arguments. The actual use case is a bit more complicated and ends up referring all the way down to a constructor with four arguments, but that shouldn't really matter.
I know I could do something like this...
private static final String TO_STRING_CONSTRUCTOR_ARGUMENT = "aflhsdlkfjlkswf";
public Entity() {
this(TO_STRING_CONSTRUCTOR_ARGUMENT);
}
public Entity(String name) {
this.name = name == TO_STRING_CONSTRUCTOR_ARGUMENT ? toString() : name;
}
... but it seems like a pretty inelegant solution.
So, any way to pull it off? Or any recommended best practices to deal with this situation?
I would prefer not to pass this around until the object is created. Instead I would do this:
public class Entity {
private final String name;
public Entity() {
this(null); // or whatever
}
public Entity(String name) {
this.name = name;
}
public String getName() {
return name != null ? name : Objects.hashCode(this);
}
}
If you can live without the final name, you can use an initializer block:
public class Entity {
private String name;
{name = this.toString();}
public Entity() {
}
public Entity(String name) {
this.name = name;
}
}
this is only available after all calls to this() or super() are done. The initializer runs first after the constructors call to super() and is allowed to access this.
As for the reasons why that is a compiler error, please see section 8.8.7 of the JLS. The reasons why this was made a compiler error are not clear, but consider that the constructor chain has to be the first thing executed when new'ing an Object and look at the order of evaluation here:
public Entity() {
this(toString());
}
toString() is evaluated first before the even the super constructor is invoked. In general this leaves open all kinds of possibilities for uninitialized state.
As a personal preference, I would suggest that everything an object needs to have in order to create valid state should be available within its constructor. If you have no way of providing valid state in a default constructor without invoking other methods defined in the object hierarchy, then get rid of the default constructor and put the onus on the users of your class to supply a valid String to your other constructor.
If you are ultimately just trying invoke the other constructor with the value of toString(), then I would suggest the following instead:
public Entity() {
name = toString();
}
which accomplishes the same goal you set out to achieve and properly initializes name.
As explained in the JLS this is not allowed before the instance is initialized.
However, there are ways to handle your scenario in a consistent manner.
As I see your case, you want to signify either a generated value (toString()) or a user provided value, which can be null.
Given this constraints, using TO_STRING_CONSTRUCTOR_ARGUMENT is failing for at least one specific use case, however obscure it may be.
Essentially you will need to replace the String with an Optional similar to what exists in Google Guava and will be included in Java 8, and seen in many other languages.
Having a StringOptional/StringHolder or whatever you choose, similar to this:
public class StringOptional {
private String value;
private boolean set = false;
public StringOptional() {}
public StringOptional(String value) {
this.value = value;
this.set = true;
}
public boolean isSet() { return set; }
public String getValue() { return value; }
}
Then you can call constructors with the knowledge of the inferred path.
public class Entity {
public Entity() {
this(New StringOptional());
}
public Entity(String s) {
this(new StringOptional(s));
}
private Entity(StringOptional optional) {
super(optional);
}
}
And store this for subsquent need:
if (optional.isSet() ? optional.getValue() : toString();
This is how I usually would handle a maybe-null scenario, hope it augments as an answer.
You cannot 'use' an instance that has not been created yet. By calling a second constructor you are postponing the creation, you cannot use it before the call or in the action of calling.
You can use a static method factory in your class Entity, and put the constructor private:
public class Entity {
private String name;
private Entity() {
}
public Entity(String name) {
this.name = name;
}
public static Entity createEntity() {
Entity result = new Entity();
result.name = result.toString();
return result;
}
}

Java Public Var question [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Property and Encapsulation
NEWB Alert!!
I am starting with Android and Java and I am starting to understand it but I am wondering why I should use getters and setters and not just public variables?
I see many people make a private variable and create a get and set method.
What is the idea here?
Its called encapsulation and the concept is central to object oriented programming. The idea is that you hide the implementation of your class and expose only the contract i.e. hide the how and only expose the what. You hide the variables by making them private and provide public setters-getters and other public methods which the clients invoke to communicate with your class. They are not tied to the actual implementation of the methods or how you store your variables.
For example, suppose you had this class where you stored a phone number as a Long object:
public class ContactInfo {
private Long phoneNo;
public Long getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(Long phoneNo) {
this.phoneNo = phoneNo;
}
}
Since the clients of the class only see the getter/setter, you can easily change the implementation of the class/methods by switching the phone number representation to a PhoneNumber object. Clients of ContactInfo wouldn't get affected at all:
public class ContactInfo {
private PhoneNumber phoneNo;
public Long getPhoneNo() {
return phoneNo.getNumber();
}
public void setPhoneNo(Long phoneNo) {
this.phoneNo = new PhoneNumber(phoneNo);
}
}
public class PhoneNumber {
private Long number;
public PhoneNumber(Long number) {
this.number = number;
}
public Long getNumber() {
return number;
}
}
The OOP concept involved is encapsulation (google it).
Some of the advantages are: you can specify different access level for setters (mutators) and getters (accessors), for example public getter and private setter. Another advantage is that you can add another code other than changing or retrieving the value. For example, you may want to check the validity of the set value, or you want to throw exceptions or raise some events in response to changing the variable to certain value. If you implement these inside an accessor or mutators, you can also change their implementations without changing any code outside of the class.
I believe the idea is "information hiding" http://en.wikipedia.org/wiki/Information_hiding
It also serves to control the access to variables (provides an interface). For example, you can provide a getter but not a setter, so that they may be read but not written. Whereas if everything was public any thing could read and write to the variables.
Also important is any checking/validation need to set a variable. For example you have a String name that is not allowed to be empty but if it is public it could easily be forgotten and set as name = "". If you have a setter such as public boolean setName(String newName) you can check newNames length and return true or false if it passes and is set or not
The concept is called encapsulation.
What it attempts to do is to separate the inner structure of a class from its behaviour.
For example, suppose a class like this
public class Point{
private float x;
private float y;
public float getX(){
return x;
}
public float getY(){
return y;
}
public float distanceToZero2(){
return x*x + y*y
}
public float getAngle(){
//havent considered the x = 0 case.
return atan(y/x);
}
public boolean isInFirstQuad(){
return x>0 && y>0;
}
}
In this case, encapsulation hides the inner structure of the class, and exposes only the operations available to a Point. If you dont like it, you can change its inner structure and mantain its behaviour (for example, changing carthesian coordinates to polar coordinates).
Anyoune who uses this class wont care about it, he /she will be happy that they have a Point class with this functionality.
Asides the encapsulation, you can also control the value get or set to your variable in some cases. For example, you want to validate the value of an age variable which should be >=1
class Person {
private int age = Integer.MIN_VALUE;
public void setAge(int age){
if(age>=1)
this.age = age;
}
public int getAge(){
return age;
}
}

How to do method chaining in Java? o.m1().m2().m3().m4()

I've seen in many Java code notation that after a method we call another, here is an example.
Toast.makeText(text).setGravity(Gravity.TOP, 0, 0).setView(layout).show();
As you see after calling makeText on the return we call setGravity and so far
How can I do this with my own classes? Do I have to do anything special?
This pattern is called "Fluent Interfaces" (see Wikipedia)
Just return this; from the methods instead of returning nothing.
So for example
public void makeText(String text) {
this.text = text;
}
would become
public Toast makeText(String text) {
this.text = text;
return this;
}
class PersonMethodChaining {
private String name;
private int age;
// In addition to having the side-effect of setting the attributes in question,
// the setters return "this" (the current Person object) to allow for further chained method calls.
public PersonMethodChaining setName(String name) {
this.name = name;
return this;
}
public PersonMethodChaining setAge(int age) {
this.age = age;
return this;
}
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
// Usage:
public static void main(String[] args) {
PersonMethodChaining person = new PersonMethodChaining();
// Output: Hello, my name is Peter and I am 21 years old.
person.setName("Peter").setAge(21).introduce();
}
}
Without method chaining
class Person {
private String name;
private int age;
// Per normal Java style, the setters return void.
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
// Usage:
public static void main(String[] args) {
Person person = new Person();
// Not using chaining; longer than the chained version above.
// Output: Hello, my name is Peter and I am 21 years old.
person.setName("Peter");
person.setAge(21);
person.introduce();
}
}
Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement. Chaining is syntactic sugar which eliminates the need for intermediate variables. A method chain is also known as a train wreck due to the increase in the number of methods that come one after another in the same line that occurs as more methods are chained together even though line breaks are often added between methods.
A similar syntax is method cascading, where after the method call the expression evaluates to the current object, not the return value of the method. Cascading can be implemented using method chaining by having the method return the current object itself (this). Cascading is a key technique in fluent interfaces, and since chaining is widely implemented in object-oriented languages while cascading isn't, this form of "cascading-by-chaining by returning this" is often referred to simply as "chaining". Both chaining and cascading come from the Smalltalk language.
From your example:
Toast.makeText(text).setGravity(Gravity.TOP, 0, 0).setView(layout).show();
Each method in the chain has to return a class or an interface. The next method in the chain has to be a part of the returned class.
We start with Toast. The method makeText, which is defined as a static method in the class Toast, has to return a class or an interface. Here, it returns an instance of the class Gravity.
The method setGravity, which is defined in the class Gravity, returns an instance of the class View,
The method setView, which is defined in the class View, returns an instance of the class JPanel.
This chain could be written out step by step.
Gravity gravity = Toast.makeText(text);
View view = gravity.setGravity(Gravity.TOP, 0, 0);
JPanel panel = view.setView(layout);
panel.show();
Writing the chain as a chain removes all of the intermediate instance variables from the source code.
Search for builder pattern or fluent interface on google to have more details about this.
Return 'this' at the end of your method can do the trick in most cases.
Adding return this; would surely help in chaining for this class but fail for sub-classes.
If you want to have the chaining behaviour inherited to the sub-classes also then change your class signature as below:
Class SuperClass < SubClass extends SuperClass >{}
This way all sub-classes will inherit method chaining.
Example:
public class SuperClass<SubClass extends SuperClass> {
public SubClass testMethod(){
return (SubClass)this;
}
public static void main(String[] args) {
SuperClass<SuperClass> superClass = new SuperClass<SuperClass>();
superClass.testMethod().testMethod().testMethod();
System.out.println(superClass.toString());
}
}
or you can use Diezel that generates all the interfaces you need based on a Regular expression of your fluent API.

Categories

Resources