This code should return the same object every time.

there is a part that i dont understand in the code. why to use private identifiers and then set/get method? why to hide your code variables/methods?

public class SingeltonEx {
	public static void main(String[] args) {
		Singelton  singelton=Singelton.getSingelton("Roni");
		
		System.out.println(singelton.getName());//Roni
		
		Singelton singelton2=Singelton.getSingelton("Udi");
		
		
		System.out.println(singelton.getName());//Roni
		
		singelton2.setName("Ela");
		
		System.out.println(singelton.getName());//Ela
	}
}
class Singelton{
	private static Singelton objSingelton; // why to hide these
	private String name;
	
	
	private Singelton(String name){
		this.name=name;
	}
	public static Singelton getSingelton(String name) {
		if(objSingelton==null){
			objSingelton=new Singelton(name);
			return objSingelton;
		}
		else {
			return objSingelton;
		}
	}
	public static Singelton getSingelton2(String name) {
		if(objSingelton==null)
			objSingelton=new Singelton(name);
			return objSingelton;
	}
	public String getName() {   // why to use set/get methods?
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

Recommended Answers

All 8 Replies

In general: if you hide your internal implementation behind gettersthen you can change the implementation without breaking any other code that uses your class. Ways in which you might change include:
Changing the private data type (eg Date to Calendar)
Waiting until someone requests a value before creating it (eg if it needs a database access).
Implementing security rules.

Setters also allow you to change the data types, but also ensure that you always know when the value changes - maybe this has effects on other things that will never get processed if the user can just change the value without you knowing. Eg
You need to update a dataabse when the value changes
You need to apply access control rules to the update
You need to recompute the sales tax if the price changes
You need to change the shipping rates if someones address is changed... etc etc

i see. so that algorithm could be written differently if security wasnt the issue.

set/get methods are only used to increase the applications security, is that right?

security yes, but also control. COnsider this:

class Employee {
  public int employeeNumber;
  public int latestHoursWorked;
...

There's nothing to stop someone doing
anEmployee.employeeNumber = -1;
and totally screwing up the database , because employeeNumber is the primary key.
or
System.out.print(anEmployee.latestHoursWorked);
is the really the latest data? the Employee class doesn't knoow it's being accessed.

Now contrast with:

class Employee {
  private int employeeNumber;
  private int latestHoursWorked;
  public int getEmplyeeNumber() {
    return employeeNumber;
  }
  public int getLatestHoursWorked() {
    // retrieve latest timeclock data from database
    // update latestHoursWorked
    return latestHoursWorked;
  }
...

see how foolproof these are?
Finally, you may be too young to remember the "millenium bug" - when all the code written in the 1980's used 2 digits to hold the year number (storage was v. expensive then). When they had to change to 4 digit years for 2000 it broke just about every program in the system. If only they had used getters! They could have changed the internal representation of the year but kept the same getter for compatibility, then added a new getter for 4 digit dates, then started a controlled switch over by adding a call to a logging routine in the old getter to find every hidden call to it.

Here's another one that just happened in a project of mine:

Class X { // old version
   private ArrayList<Stuff> theData = ...
   public Collection<Stuff> getData() {
      return theData;
   }

but then there was a new need to have the data accessed by a String ID, which cuased me to change the data to

private Hashtable<String, Stuff> = ...

which would have broken the rest of the code if theData had been public.
But I just changed the getter to

public Collection<Stuff> getData() {
      return theData.values();
   }

and everything was OK

so in the employee class the private int latestHourWorked; has a value?
you dont want that value to change when someone tries to update the method/values, is thats why you create the set/get methods... they carry out the updating?

i can see that my class Singleton is quite protected cause it lets you return the same object , no matter what you do

Yes. and Yes.

The problem with "knowing" that the same object will always be returned is that things change. If you start with public variables you are stuck with them, even if sometime later, someone gives you a new requirement that means you would like to protect or change them hidden behind a getter and/or setter. Of course this won't happen in a single school assignment, but it happens all the time in real life. SO real programmers use getters and setters all the time* and know that that's the safest thing to do**
* The one exception is where you declare a final variable and initialise it in the declaration, because by definition it can never change. This is often used to create "public constants" eg public static final float PI = 3.14159;
** they also use IDE's such as Netbeans or Eclipse that will generate the methods for you.

whats the difference between.

final int method()

and

private int method()

and

private final int variable?

final for a variable means its value, once set, can never be changed. Final for a method means cannot be overridden in a subclass. Private for a method or a variable means it can only be accessed from within that class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.