Best practice for subclass/superclass fields [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am having trouble deciding between these three ways to handle field variables for a subclass and superclass.
Method 1:
public abstract class Vehicle {
public abstract int getNumberOfWheels();
public abstract int getCost();
}
public class Car extends Vehicle {
private int numberOfWheels;
private int cost;
public Car() {
this.numberOfWheels = 4;
this.cost = 10000;
}
public int getNumberOfWheels() {
return numberOfWheels;
}
public int getCost() {
return cost;
}
}
With this method i have to implement the same duplicate getter methods in every subclass of Vehicle. I imagine this would be a problem with more complicated getter method, that have to be duplicated and eventually maintained.
Method 2:
public abstract class Vehicle {
private int numberOfWheels;
private int cost;
public int getNumberOfWheels() {
return numberOfWheels;
}
public int getCost() {
return cost;
}
public void setNumberOfWheels(int numberOfWheels) {
this.numberOfWheels = numberOfWheels;
}
public void setCost(int cost) {
this.cost = cost;
}
}
public class Car extends Vehicle {
private int numberOfWheels;
private int cost;
public Car() {
super.setNumberOfWheels(4);
super.setCost(10000);
}
}
With this method i have to implement setter methods that i might not want to have. I might not want other classes to be able to change the fields, even in the same package.
Method 3:
public abstract class Vehicle {
private int numberOfWheels;
private int cost;
public class Vehicle(int numberOfWheels, int cost) {
this.numberOfWheels = numberOfWheels;
this.cost = cost;
}
public int getNumberOfWheels() {
return numberOfWheels;
}
public int getCost() {
return cost;
}
}
public class Car extends Vehicle {
private int numberOfWheels;
private int cost;
public Car() {
super(4, 10000);
}
}
With this method and with a lot of fields, the amount of constructor parameters will grow huge, which just feels wrong.
It seems like this would be a common enough problem for there to exist some kind of "best practice". Is there a best way to do this?

Several thoughts here:
It is actually good that you don't get into the protected fields story; one should avoid sharing fields between base/extending classes if possible.
Similarly, it is also good practice to avoid using setters. That kinda rules out your second options.
Further on ...
You could rewrite your subclass in option 1 to:
#Override // always use that when OVERRIDING methods!
public int getNumberOfWheels() { return 4; }
In your option 1, those numbers are actually constants as your code is not showing any means to change those values. So there is no need to use fields in the derived classes! Unless of course, you might imagine different types of Cars, and a need to allow for 3 or 5 wheels as well. In that case, you would offer a default ctor; and one that takes that number-of-wheels (to then store it in some final property).
Then: you are correct, when a lot of information would be required, that option3 using constructors will "blow up" on you. But: that would be just a consequence of a design problem anyway. Because: one should be conservative about number of fields anyway. Meaning: if your class carries so many fields that init'ing them via constructors looks like a problem, than that is an indication that you got too many fields in the first place! In such a situation, you would look into your model to figure which properties really belong into your class.
Example: in your code, you are representing "cost" as property of your base class. But is that really true? Is its "prize" really an essential property of any vehicle? What I mean is: a car is just a car; it doesn't "care" about its value. That value is some extrinsic property, that other systems would impose on that car. Meaning: a vehicle doesn't necessarily need a price/cost property. You only start thinking about that when vehicles are entities in some bigger context that deals with the values of its entities. So some other EntityManager thingy might be a better place to keep track of vehicles and their corresponding (current) value.

Good practice is rather relative here; in your case, it depends on what you are trying to achieve.
Will any subclass of Vehicle have a number of wheels and a cost associated? If the answer is Yes, then it is good practice to add them to the superclass. If you may have TrackVehicle as subclass, then numberOfWheels is not applicable here and hence does not belong in the superclass.
Ask yourself the question: do you really need setters? Will you have to change the state of your instance after creation? If not, don't add them: you can create a constructor in the superclass that takes the total number of required parameters and use it in every subclass:
public Car(int numberOfWheels, int cost) {
super(numberOfWheels, cost);
}
By trying to guess your intention, this would be my method of doing it:
public abstract class Vehicle {
private int numberOfWheels;
private int cost;
public Vehicle(int numberOfWheels, int cost) {
this.numberOfWheels = numberOfWheels;
this.cost = cost;
}
public int getNumberOfWheels() {
return numberOfWheels;
}
public int getCost(){
return cost;
}
}
and a specific subclass where every Car has 4 wheels and a cost for the outside world that is actually much bigger than the initial one (just to show the fact that you can override a method if required, no need to duplicate it)
public class Car extends Vehicle {
public Car(int cost) {
super(4, cost);
}
#Override
public int getCost(){
return cost * 2;
}
}
About the 'constructor parameters will grow huge' problem: have a look at the 'Builder' design patters. (Effective Java - Builder pattern)

I am having trouble deciding between these three ways to handle field variables for a subclass and superclass.
In the first place you should prefer composition over inheritance which means that concrete classes do not inherit from each other, only interfaces.
Beside this your question somehow depends on the purpose of your classes.
Classes can either be "plain value classes" without any business logic (aka data transfer objects - DTOs) or "regular" objects.
DTOs
When you're desining DTOs you should create them as beans which means that you should create public getter methods for each property. By any chance you should make your DTOs immutable which means all member variables are declared with the final keyword. Then you have to set the values via constructor.
However: some frameworks require DTOs with default constructors and setters for the member variables.
regular objects
In all other classes you should not provide access to member variables of a class neither directly nor via getters/setters. This would violate the most important OO principle: information hiding aka encapsulation.
Initial values should be set via constructor and when you have the need to modify a member value you should provide methods with business related names.
eg.:
class Vehicle {
private int speedInMph;
private final int maximumSpeedInMph;
public Vehicle(int initialSpeedInMph, int maximumSpeedInMph){
this.speedInMph=initialSpeedInMph;
this.maximumSpeedInMph=maximumSpeedInMph;
}
public void accelerateBy(int accelerationInMph){
this.speedInMph+=accelerationInMph;
if(maximumSpeedInMph<this.speedInMph)
this.speedInMph=maximumSpeedInMph;
}
public void decelerateBy(int decelerationInMph){
this.speedInMph-=decelerationInMph;
if(0>this.speedInMph)
this.speedInMph=0;
}
}

Related

Java encapsulation concept not very clear

I have a bit of confusion with encapsulation concept. I have gone through quite a few answers on the same , but still confused. As far as I understand, encapsulation is to make instance variables as private so that outside cannot access this directly. Public getter and setter methods would be provided to access the private variables.
Suppose we have a class like below :
class Address
{
int doorNumber;
public int getDoorNumber()
{
//some code
}
public void setDoorNumber(int doorNumber)
{
//some code
}
}
We have another class from which we are trying to access the variable of Address class.
class TestAddress
{
public static void main()
{
Address add=new Address();
add.doorNumber=10; //cannot be done
add.setDoorNumber(10);
}
}
Though we are not accessing the variable directly , we are still modifying doorNumber using setter method to set the value of it to 10 . Basically the outside world can still access the private field and modify it in the way it wants. I do not understand what is the point of having encapsulation then . Can you please provide me some examples to understand encapsulation . Also scenarios where encapsulation was not used and problems which can occur because of that.
Look at the following counter-example:
class Address
{
int floor, door;
public int getDoorNumber()
{
return floor*100+door;
}
public void setDoorNumber(int doorNumber)
{
int newFloor=doorNumber/100;
if(newFloor<0 || newFloor>6)
throw new IllegalArgumentException("no such door "+doorNumber);
floor=newFloor;
door=doorNumber-newFloor*100;
}
}
The code calling setDoorNumber(10) still works without needing any change. The independence of the property “doorNumber” from the object’s internal representation, plus the possibility to validate the input value, are the key point of encapsulation. You can’t do that with a field like public int doorNumber;
Besides that, there are developers considering a method like setDoorNumber(int) being contradicting encapsulation, or at least, be a weak form of encapsulation. A stronger encapsulation model would work without such a public setter method but providing high-level operations only. Such an operation, like booking a room in a hotel would perform much more related operations, involving other objects, and consistency checks before internally assigning a room number to an address…
Using getters and setters has some benefits over making fields public :
You can redesign the internals of your class by replacing int doorNumber; with one or more fields of possibly different type. In such a case you can keep the getter and setter and that means other classes wouldn't have to be modified. If you had preferred private fields, any change in this class would enforce changes in any other class that uses it.
You can add validation and or reformatting logic inside a setter or getter, without changing the type of the field. Otherwise, if you used public fields, this logic would have to be repeated in any other class that accesses this field.
You can read more about it at Effective Java item 14
Consider this example:
public class Address {
private int doorNumber;
public int getDoorNumber() {
return doorNumber;
}
public void setDoorNumber(int doorNumber) {
if (doorNumber <= 0) {
throw new IllegalArgumentException("door number must be > 0");
}
this.doorNumber = doorNumber;
}
}
If the doorNumber field was declared as public, some code could violate the constraint that the door numbers in addresses should be positive numbers.
Consider this example:
public class Address {
private String doorNumber;
public int getDoorNumber() {
return Integer.parseInt(doorNumber);
}
public String getDoorNumber2() {
return doorNumber;
}
public void setDoorNumber(int doorNumber) {
this.doorNumber = doorNumber + "";
}
public void setDoorNumber(String doorNumber) {
this.doorNumber = doorNumber;
}
}
Note that we evolving our API so that we can represent the address "221B Baker St, London", but still allowing our old "house numbers are integers" API to be used ... (sort of).
But if doorNumber had been public, then we would have been forced to change every place in the codebase where Address.doorNumber had been used.

Is this the correct way to build class hierarchy?

Ok, so I have whole module that is in charge of generating player class in my game and after hours and hours of hard labour I came up with this hierarchy (snippets of code without making it too graphic but still providing enough to go on)
I have a base interface for Entities (which are either Player or Monsters):
public interface Entity {
public int getHP();
...
// all getters that denote all stats the Entities have in my game, nothing
else is in the interface
}
Then there is second interface extending Entity, called Classes, that contains all the setters relevant to classes:
public interface Classes extends Entity {
void setHP(int a);
... //and so on}
Finally getting to some real class, class PlayerClasses is responsible for building the classes:
public class PlayerClasses implements Classes {
private int HP, ATK, DEF, DAMAGE, DROP;
#Override
public int getHP() {
return HP;
}
#Override
public void setHP(int a) {
HP = a;
}
// this is how I build the player class
public void Rogue(){
setHP(150);
setATK(30);
setDEF(20);
setDAMAGE();
}
And finally a class which constructor is used to create the player instance that is then passed into other modules (no inheritance or direct access to any other class field or requiring any state in constructor, so win right?)
public class Player {
private int HP,ATK,DEF,DAMAGE,DROP;
private PlayerClasses c;
public Player() {
c = new PlayerClasses();
c.Rogue();
HP = c.getHP();
ATK = c.getATK();
DEF = c.getDEF();
DAMAGE = c.getDAMAGE();
DROP = c.getDrop();
}
Kind of long question, but I tried to keep it civil. Any feedback is very appreciated.
Edit: Ok to clarify why I choose to design like this, I want the player instance to be immutable object that can only be instanced with correct values, while keeping the initialization in other modules as clean as possible without any dependencies. So for example values from two different player classes cannot mix up in case it is instances in module that shows player stats and monster stats. I feel passing private HP and ATK variables in inheritance and then pulluting namespace with same variables is not a way to go for example.
I think I don't understand the reason for an immutable Player class that contains a PlayerClass. But anyways, IMO your Player class is what should inherit the Entity trait. Not the PlayerClasses object that is used as sort of template(?). Because what's the point of having a Player and I assume a similarly constructed Monster class if they aren't both Entity?
You also mix responsibilites / abstractions in an odd way. What is it that is encapsulated in the PlayerClasses and in the Player? PlayerClasses looks like it should represent the class type like "Rogue", not the actual player. And for that it shouldn't have setter methods and neither is a class type an entity.
And a factory like method that initializes a PlayerClasses object is "bad" style. You should always try to guarantee based only on class type that things are right, not have magic methods that need to be called for objects to be right (i.e. no init methods besides the constructor).
Take for example a method that takes a PlayerClasses object as parameter and you want someone else to use that code. They see that they need a reference to PlayerClass and a no-argument constructor for that class, but they can't know what all the initialization steps are. Constructor or various factory / builder patterns can guarantee exactly that.
Here's a draft of how I would have done it:
interface PlayerClass {
int getBaseHp();
int getBaseAtk();
... // more class attributes
}
// as utility so I don't have to write 20 full classes
abstract class PlayerClassBase implements PlayerClass {
private final int hp, atk, ..;
protected PlayerClassBase(int hp, int atk, ...) {
this.hp = hp;
this.atk = atk;
}
#Override
public int getBaseHp() {
return hp;
}
....
}
// short class but guaranteed that every instance of Rogue has the correct values
class Rogue {
public Rogue() {
super(40, 23, 123, ...);
}
}
// something to represent entities
interface Entity {
int getCurrentHp();
int takeDamageFrom(Entity other);
...
}
// maybe an abstract base class here as well
// represents a player that has an immutable class and it can't exist without
class Player implements Entity {
privte final PlayerClass playerClass;
private int currentHp;
...
public Player(PlayerClass playerClass) {
this.playerClass = playerClass;
currentHp = playerClass.getHp();
...
}
public int takeDamageFrom(Entity other) {
currentHp -= other.getCurrentAtk();
return currentHp;
}
}
The PlayerClass part could also be a simple enum instead of a big class hierarchy.
enum PlayerClass {
ROGUE(23, 23, 4, ...),
...
;
private final int hp;
PlayerClass(int hp, int atk, ...) {
this.hp = hp;
...
}
public int getHp() { return hp; }
...
}
That way you could statically reference PlayerClass.ROGUE and create a player like this: new Player(PlayerClass.ROGUE). Instead of currently new Player(new PlayerClass().Rogue()). Or with the big hierarchy: new Player(new Rogue())

Java how do I use a set Method? [duplicate]

How can I use the set and get methods, and why should I use them? Are they really helpful? And also can you give me examples of set and get methods?
Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.
For example, for a member variable:
Integer x;
You might have methods:
Integer getX(){ return x; }
void setX(Integer x){ this.x = x; }
chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public get method and keeping the set private or not providing a set at all.
I want to add to other answers that setters can be used to prevent putting the object in an invalid state.
For instance let's suppose that I've to set a TaxId, modelled as a String. The first version of the setter can be as follows:
private String taxId;
public void setTaxId(String taxId) {
this.taxId = taxId;
}
However we'd better prevent the use to set the object with an invalid taxId, so we can introduce a check:
private String taxId;
public void setTaxId(String taxId) throws IllegalArgumentException {
if (isTaxIdValid(taxId)) {
throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
}
this.taxId = taxId;
}
The next step, to improve the modularity of the program, is to make the TaxId itself as an Object, able to check itself.
private final TaxId taxId = new TaxId()
public void setTaxId(String taxIdString) throws IllegalArgumentException {
taxId.set(taxIdString); //will throw exception if not valid
}
Similarly for the getter, what if we don't have a value yet? Maybe we want to have a different path, we could say:
public String getTaxId() throws IllegalStateException {
return taxId.get(); //will throw exception if not set
}
I think you want something like this:
public class Person {
private int age;
//public method to get the age variable
public int getAge(){
return this.age
}
//public method to set the age variable
public void setAge(int age){
this.age = age;
}
}
You're simply calling such a method on an object instance. Such methods are useful especially if setting something is supposed to have side effects. E.g. if you want to react to certain events like:
public void setAge(int age){
this.age = age;
double averageCigarettesPerYear = this.smokedCigarettes * 1.0 / age;
if(averageCigarettesPerYear >= 7300.0) {
this.eventBus.fire(new PersonSmokesTooMuchEvent(this));
}
}
Of course this can be dangerous if somebody forgets to call setAge(int) where he should and sets age directly using this.age.
Setters and getters are used to replace directly accessing member variables from external classes. if you use a setter and getter in accessing a property, you can include initialization, error checking, complex transformations, etc. Some examples:
private String x;
public void setX(String newX) {
if (newX == null) {
x = "";
} else {
x = newX;
}
}
public String getX() {
if (x == null) {
return "";
} else {
return x;
}
}
Having accessor methods is preferred to accessing fields directly, because it controls how fields are accessed (may impose data checking etc) and fits with interfaces (interfaces can not requires fields to be present, only methods).
Some benefits of using getters and setters (known as encapsulation or data-hiding):
(originally answered here)
1. The fields of a class can be made read-only (by only providing the getter) or write-only (by only providing the setter). This gives the class a total control of who gets to access/modify its fields.
Example:
class EncapsulationExample {
private int readOnly = -1; // this value can only be read, not altered
private int writeOnly = 0; // this value can only be changed, not viewed
public int getReadOnly() {
return readOnly;
}
public int setWriteOnly(int w) {
writeOnly = w;
}
}
2. The users of a class do not need to know how the class actually stores the data. This means data is separated and exists independently from the users thus allowing the code to be more easily modified and maintained. This allows the maintainers to make frequent changes like bug fixes, design and performance enhancements, all while not impacting users.
Furthermore, encapsulated resources are uniformly accessible to each user and have identical behavior independent of the user since this behavior is internally defined in the class.
Example (getting a value):
class EncapsulationExample {
private int value;
public int getValue() {
return value; // return the value
}
}
Now what if I wanted to return twice the value instead? I can just alter my getter and all the code that is using my example doesn't need to change and will get twice the value:
class EncapsulationExample {
private int value;
public int getValue() {
return value*2; // return twice the value
}
}
3. Makes the code cleaner, more readable and easier to comprehend.
Here is an example:
No encapsulation:
class Box {
int widthS; // width of the side
int widthT; // width of the top
// other stuff
}
// ...
Box b = new Box();
int w1 = b.widthS; // Hm... what is widthS again?
int w2 = b.widthT; // Don't mistake the names. I should make sure I use the proper variable here!
With encapsulation:
class Box {
private int widthS; // width of the side
private int widthT; // width of the top
public int getSideWidth() {
return widthS;
}
public int getTopWIdth() {
return widthT;
}
// other stuff
}
// ...
Box b = new Box();
int w1 = b.getSideWidth(); // Ok, this one gives me the width of the side
int w2 = b.getTopWidth(); // and this one gives me the width of the top. No confusion, whew!
Look how much more control you have on which information you are getting and how much clearer this is in the second example. Mind you, this example is trivial and in real-life the classes you would be dealing with a lot of resources being accessed by many different components. Thus, encapsulating the resources makes it clearer which ones we are accessing and in what way (getting or setting).
Here is good SO thread on this topic.
Here is good read on data encapsulation.
The above answers summarize the role of getters and setters better than I could, however I did want to add that your code should ideally be structured to reduce the use of pure getters and setters, i.e. those without complex constructions, validation, and so forth, as they break encapsulation. This doesn't mean you can't ever use them (stivlo's answer shows an example of a good use of getters and setters), just try to minimize how often you use them.
The problem is that getters and setters can act as a workaround for direct access of private data. Private data is called private because it's not meant to be shared with other objects; it's meant as a representation of the object's state. Allowing other objects to access an object's private fields defeats the entire purpose of setting it private in the first place. Moreover, you introduce coupling for every getter or setter you write. Consider this, for example:
private String foo;
public void setFoo(String bar) {
this.foo = bar;
}
What happens if, somewhere down the road, you decide you don't need foo anymore, or you want to make it an integer? Every object that uses the setFoo method now needs to be changed along with foo.
just because the OOP rule: Data Hiding and Encapsulation. It is a very bad practice to declare a object's as public and change it on the fly in most situations. Also there are many other reasons , but the root is Encapsulation in OOP. and "buy a book or go read on Object Oriented Programming ", you will understand everything on this after you read any book on OOP.
The benefits of get() set() methods are as follows ..
You can serialize you object easily.
You can create a persistent object from the containing class.
You can convert the properties to JSON easily.
In the DAO layer (Frameworks like Hibernate) you can directly save the object to DB.
Easy understanding of object oriented concept.
Needs in all design pattern except possibly in single tone pattern.
Security for properties protecting direct access.
Polymorphism, Encapsulation can be easily understood and implemented by this type of class.
Example:
private String personName;
private int personId;
public void setPersonName(String name) throws Exception{
if(!(name.equals("")||name=="")){
this.personName = name;
}
}
public String getPersonName(){
return this.personName;
}
public void setPersonId(int id) throws Exception{
this.personId = id;
}
public int getPersonId(){
return this.personId;
}
Above answers all assume that the object in question is an object with behaviour.
An advanced strategy in OOP is to separate data objects (that do zip, only have fields) and behaviour objects.
With data objects, it is perfectly fine to omit getters and instead have public fields. They usually don't have setters, since they most commonly are immutable - their fields are set via the constructors, and never again.
Have a look at Bob Martin's Clean Code or Pryce and Freeman's Growing OO Software... for details.
public class Person{
private int age;
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
}
i think this is you want..
and this also called pojo
this is the code for set method
public void setAge(int age){
this.age = age;
}
It looks like you trying to do something similar to C# if you want setAge create method setAge(int age){
this.age = age;}
I don't see a simple answer to the second question (why) here. So here goes.
Let's say you have a public field that gets used very often in your code. Whenever you decide you need to do something extra before you give or set this field you have a problem. You have to create a special getter and setter for this field and change your complete code from using the field directly to using the getter and setters.
Now imagine you are developing a library widely used by many people. When you need to make a change like the above and set direct access of the field to private the code of all the people using this field will break.
Using getters and setters is about future planning of the code, it makes it more flexible. Of course you can use public fields, especially for simple classes that just hold some data. But it's always a good idea to just make the field privately and code a get and set method for it.
This answer is merged from another question.
Your getAge() method is called instance method in Java.
To invoke an instance method, you should have a object of the Class in which this method is defined.
For Example, If this method in a Class called Person, then
Create a Person object using new operator
Person p = new Person();
To get the age of a Person object, use this method
p.getAge()
Although still a second year undergraduate student I will say my opinion. I believe that Java and private variables within your class are "RULES". Therefore because the variables in your class are private I think you use getters and setters to be able to define these variables outside the class.

Specifying method in getter/setter

To actually understand the meaning of encapsulation, example that class private fields must be accessed through class public methods is as per definition, but actually stll it doesn't make difference as the field is still accessible as it is.
So,I think there should be some processing inside getters/setters to hide how the field is being handled. But it breaks the principal of behind pojos. How can one handle this situation?
I'm not sure what according to you is "the principle of POJOs". The following is a POJO and still hides implementation details behind getters and setters:
public class Example {
private int thousands;
private int units;
public void setValue(int value) {
thousands = value / 1000;
units = value % 1000;
}
public int getValue() {
return 1000 * thousands + units;
}
}
Encapsulation means not to expose the internals of your class.
In the Java context it means that the attributes of your class should NOT be accessible by other classes, instead your class should provide methods that will allow to access the attributes. In cases of POJO classes these methods will only allow to set (setters) and get (getters) the values of the attributes from the POJO class.
The goal of encapsulation is to protect the attributes of your class from being modified by other classes. Your class is obviously able to do whatever you want with the attributes inside your classes.
No, the field is not accessible as it is. All it takes to make a method a getter or a setter ist the proper signature.
public String getFoo() {
return null;
}
This is a perfect getter for a String foo, even though it returns null.
public void setFoo(String foo) {
// do nothing
}
This is a perfect setter for the same member, even though it does nothing.
One of the many uses of getters and setters is to restrict the value of the variable. By making the data members private and keeping the getters and setters public, the programmer can keep a check on the value of the variable. For ex:
class Employee
{
private int age;
public int getAge()
{
return this.age;
}
public void setAge(int age)
{
if(age<18 || age>60)
this.age = age;
else
System.out.println("The age of the employee should be between 18 and 60");
}
}
In this case the age of the Employee can never be more less than 18 and more than 60.
Don't know why people usually mix Data Encapsulation with Data hiding. Data encapsulation simply means grouping data together whereas data hiding is a way to store this data so others cannot know it's internal implementation.
Lets say you have a class PersonalInfo in which you have fields like name,gender,age etc. As a programmer(which you are) you will provide user some way to enter these fields, save them in your PersonalInfo object using setter methods.IF user wish to see the information you simple call getters and display information. Your implementation as in you may store this variables in a map may varry. So you can say
public void setName(String name){
SomeMap.add("name",name);
}
Note *you are the programmer and you will always know the implementatio*n. Keeping the fields private is to allow only your class methods to access your data.
Imagine it this way. User can create an object. He may set all fields using getters and setters. It may be your implementation to calculate age using DOB(Date of Birth) in which case you will not provide setter for age. In this case user cannot say myObj.age=23. This is purely your implementation.Hope this clears the confusion!
It's still accessible but you see when you use it directly (public variable) you can change the value of variable without any restriction. The advantage of using such kind of private variables with setter and getter methods is that you can write code inside the setter method to check whether the value set is in the expected range or not. Or you can even store the value in different form than the apparent view. For example you may store the value of a variable by adding offset to the value of the parameter of the setter method and in getter method you may just revert back the process(Encapsulation). When the value set is not in the expected range you may even throw exceptions.
Example1:
Here var1 is a private variable
public void setValue(int var1){
if(var1<0){
//throw exception
}
this.var1=var1;
}
Example2:
public void setValue(int var1){
this.var1=calculatesomething+var1;
}
public int getValue(){
return calculatesomething+this.var1;
}
That's the use of encapsulation.....all the best
Encapsulation is to restrict the access to the Class's variables and to regularize the way of editing them.
Class Test
{
public int a;
public Test()
{
a = 0;
}
public getA()
{
return a;
}
public setA(int a)
{
this.a = a
}
}
Class TestMain
{
main()
{
Test t = new Test();
System.out.println(t.a); // This prints 0;
int a = t.getA();
a = 10;
System.out.println(t.a); // This still prints 0;
t.a = 20;
System.out.println(t.a); // This prints 20;
}
}
In the above example the programmer may not be intentionally changing the value of t.a but the value changes.
If he really intents to change it, then he should use the setter.
Encapsulation is the feature that java provides which solves certain practical problems and helps in extensibility.
If the Test and TestMain classes are written by same person, there wont't be any confusion.
But practically that is not the case.

Set and Get Methods in java?

How can I use the set and get methods, and why should I use them? Are they really helpful? And also can you give me examples of set and get methods?
Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.
For example, for a member variable:
Integer x;
You might have methods:
Integer getX(){ return x; }
void setX(Integer x){ this.x = x; }
chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public get method and keeping the set private or not providing a set at all.
I want to add to other answers that setters can be used to prevent putting the object in an invalid state.
For instance let's suppose that I've to set a TaxId, modelled as a String. The first version of the setter can be as follows:
private String taxId;
public void setTaxId(String taxId) {
this.taxId = taxId;
}
However we'd better prevent the use to set the object with an invalid taxId, so we can introduce a check:
private String taxId;
public void setTaxId(String taxId) throws IllegalArgumentException {
if (isTaxIdValid(taxId)) {
throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
}
this.taxId = taxId;
}
The next step, to improve the modularity of the program, is to make the TaxId itself as an Object, able to check itself.
private final TaxId taxId = new TaxId()
public void setTaxId(String taxIdString) throws IllegalArgumentException {
taxId.set(taxIdString); //will throw exception if not valid
}
Similarly for the getter, what if we don't have a value yet? Maybe we want to have a different path, we could say:
public String getTaxId() throws IllegalStateException {
return taxId.get(); //will throw exception if not set
}
I think you want something like this:
public class Person {
private int age;
//public method to get the age variable
public int getAge(){
return this.age
}
//public method to set the age variable
public void setAge(int age){
this.age = age;
}
}
You're simply calling such a method on an object instance. Such methods are useful especially if setting something is supposed to have side effects. E.g. if you want to react to certain events like:
public void setAge(int age){
this.age = age;
double averageCigarettesPerYear = this.smokedCigarettes * 1.0 / age;
if(averageCigarettesPerYear >= 7300.0) {
this.eventBus.fire(new PersonSmokesTooMuchEvent(this));
}
}
Of course this can be dangerous if somebody forgets to call setAge(int) where he should and sets age directly using this.age.
Setters and getters are used to replace directly accessing member variables from external classes. if you use a setter and getter in accessing a property, you can include initialization, error checking, complex transformations, etc. Some examples:
private String x;
public void setX(String newX) {
if (newX == null) {
x = "";
} else {
x = newX;
}
}
public String getX() {
if (x == null) {
return "";
} else {
return x;
}
}
Having accessor methods is preferred to accessing fields directly, because it controls how fields are accessed (may impose data checking etc) and fits with interfaces (interfaces can not requires fields to be present, only methods).
Some benefits of using getters and setters (known as encapsulation or data-hiding):
(originally answered here)
1. The fields of a class can be made read-only (by only providing the getter) or write-only (by only providing the setter). This gives the class a total control of who gets to access/modify its fields.
Example:
class EncapsulationExample {
private int readOnly = -1; // this value can only be read, not altered
private int writeOnly = 0; // this value can only be changed, not viewed
public int getReadOnly() {
return readOnly;
}
public int setWriteOnly(int w) {
writeOnly = w;
}
}
2. The users of a class do not need to know how the class actually stores the data. This means data is separated and exists independently from the users thus allowing the code to be more easily modified and maintained. This allows the maintainers to make frequent changes like bug fixes, design and performance enhancements, all while not impacting users.
Furthermore, encapsulated resources are uniformly accessible to each user and have identical behavior independent of the user since this behavior is internally defined in the class.
Example (getting a value):
class EncapsulationExample {
private int value;
public int getValue() {
return value; // return the value
}
}
Now what if I wanted to return twice the value instead? I can just alter my getter and all the code that is using my example doesn't need to change and will get twice the value:
class EncapsulationExample {
private int value;
public int getValue() {
return value*2; // return twice the value
}
}
3. Makes the code cleaner, more readable and easier to comprehend.
Here is an example:
No encapsulation:
class Box {
int widthS; // width of the side
int widthT; // width of the top
// other stuff
}
// ...
Box b = new Box();
int w1 = b.widthS; // Hm... what is widthS again?
int w2 = b.widthT; // Don't mistake the names. I should make sure I use the proper variable here!
With encapsulation:
class Box {
private int widthS; // width of the side
private int widthT; // width of the top
public int getSideWidth() {
return widthS;
}
public int getTopWIdth() {
return widthT;
}
// other stuff
}
// ...
Box b = new Box();
int w1 = b.getSideWidth(); // Ok, this one gives me the width of the side
int w2 = b.getTopWidth(); // and this one gives me the width of the top. No confusion, whew!
Look how much more control you have on which information you are getting and how much clearer this is in the second example. Mind you, this example is trivial and in real-life the classes you would be dealing with a lot of resources being accessed by many different components. Thus, encapsulating the resources makes it clearer which ones we are accessing and in what way (getting or setting).
Here is good SO thread on this topic.
Here is good read on data encapsulation.
The above answers summarize the role of getters and setters better than I could, however I did want to add that your code should ideally be structured to reduce the use of pure getters and setters, i.e. those without complex constructions, validation, and so forth, as they break encapsulation. This doesn't mean you can't ever use them (stivlo's answer shows an example of a good use of getters and setters), just try to minimize how often you use them.
The problem is that getters and setters can act as a workaround for direct access of private data. Private data is called private because it's not meant to be shared with other objects; it's meant as a representation of the object's state. Allowing other objects to access an object's private fields defeats the entire purpose of setting it private in the first place. Moreover, you introduce coupling for every getter or setter you write. Consider this, for example:
private String foo;
public void setFoo(String bar) {
this.foo = bar;
}
What happens if, somewhere down the road, you decide you don't need foo anymore, or you want to make it an integer? Every object that uses the setFoo method now needs to be changed along with foo.
just because the OOP rule: Data Hiding and Encapsulation. It is a very bad practice to declare a object's as public and change it on the fly in most situations. Also there are many other reasons , but the root is Encapsulation in OOP. and "buy a book or go read on Object Oriented Programming ", you will understand everything on this after you read any book on OOP.
The benefits of get() set() methods are as follows ..
You can serialize you object easily.
You can create a persistent object from the containing class.
You can convert the properties to JSON easily.
In the DAO layer (Frameworks like Hibernate) you can directly save the object to DB.
Easy understanding of object oriented concept.
Needs in all design pattern except possibly in single tone pattern.
Security for properties protecting direct access.
Polymorphism, Encapsulation can be easily understood and implemented by this type of class.
Example:
private String personName;
private int personId;
public void setPersonName(String name) throws Exception{
if(!(name.equals("")||name=="")){
this.personName = name;
}
}
public String getPersonName(){
return this.personName;
}
public void setPersonId(int id) throws Exception{
this.personId = id;
}
public int getPersonId(){
return this.personId;
}
Above answers all assume that the object in question is an object with behaviour.
An advanced strategy in OOP is to separate data objects (that do zip, only have fields) and behaviour objects.
With data objects, it is perfectly fine to omit getters and instead have public fields. They usually don't have setters, since they most commonly are immutable - their fields are set via the constructors, and never again.
Have a look at Bob Martin's Clean Code or Pryce and Freeman's Growing OO Software... for details.
public class Person{
private int age;
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
}
i think this is you want..
and this also called pojo
this is the code for set method
public void setAge(int age){
this.age = age;
}
It looks like you trying to do something similar to C# if you want setAge create method setAge(int age){
this.age = age;}
I don't see a simple answer to the second question (why) here. So here goes.
Let's say you have a public field that gets used very often in your code. Whenever you decide you need to do something extra before you give or set this field you have a problem. You have to create a special getter and setter for this field and change your complete code from using the field directly to using the getter and setters.
Now imagine you are developing a library widely used by many people. When you need to make a change like the above and set direct access of the field to private the code of all the people using this field will break.
Using getters and setters is about future planning of the code, it makes it more flexible. Of course you can use public fields, especially for simple classes that just hold some data. But it's always a good idea to just make the field privately and code a get and set method for it.
This answer is merged from another question.
Your getAge() method is called instance method in Java.
To invoke an instance method, you should have a object of the Class in which this method is defined.
For Example, If this method in a Class called Person, then
Create a Person object using new operator
Person p = new Person();
To get the age of a Person object, use this method
p.getAge()
Although still a second year undergraduate student I will say my opinion. I believe that Java and private variables within your class are "RULES". Therefore because the variables in your class are private I think you use getters and setters to be able to define these variables outside the class.

Categories