Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am having difficulty understanding constructors and set/get methods.

What are they being used for? If someone can explain a little more hopefully I can get the AHA moment.

share|improve this question
1  
Constructors and get/set methods exist in other programming languages, not just Java. –  Bernard Mar 21 '12 at 2:46
14  
How did he describe them? Telling us what you currently understand will show you put some effort into this question and didn't just give us your homework assignment. Is Google down? –  JeffO Mar 21 '12 at 13:06
    
Basically he had 2 projects open, the first one he called "driver" and the second one with all the constructors and the get/set methods. when he ran the program, driver was pulling data from the second project. but when he explains it that is when i could not understand. –  Programmerwannabe Mar 21 '12 at 23:15
2  
@s4m 5k views and 7 answers, how much more attention do you think it warrants? –  AakashM Aug 22 '13 at 7:58
2  
@AakashM this is an essential question and I want more experts to come up with more interesting answers, that's all. –  S4M Aug 22 '13 at 19:11

12 Answers 12

Constructor

Used to initialize an object of the class and any members. Called only once for the lifetime of the object being initialized:

public class Person
{
   // Member.
   private String _name;

   // Constructor.
   public Person(String name)
   {
      _name = name;
   }
}

Example usage:

// Initialize object of Person class by calling constructor.
Person person = new Person("John Smith");

Get/Set Methods

Used to get or set values of object members respectively. Unlike constructors, set methods can be used to initialize member values more than once:

public class Person
{
    // Member.
    private String _name;

    // Get member value.
    public String getName()
    {
       return _name;
    }

    // Set member value to given value.
    public void setName(String name)
    {
       _name = name;
    }
}

Example usage:

// Initialize object of Person class.
Person person = new Person("John Smith");

// Get name of this person.
String name = person.getName();

// Set new name for this person.
person.setName("John Doe");
share|improve this answer
5  
Tip: NEVER change anything with a get function! –  Jeffrey Sweeney Mar 21 '12 at 2:47
2  
@JeffreySweeney, How about lazy loading techniques? –  Michael Kjörling Mar 21 '12 at 13:53
1  
@MichaelKjörling ...maybe, assuming that something's initialization status doesn't affect anything (and it often does unintentionally). –  Jeffrey Sweeney Mar 21 '12 at 13:56
6  
@JeffreySweeney: I think the technically (and pedantically correct) rule would be "calling a getter should have no observable effect, except for the returned value". –  Joachim Sauer Mar 22 '12 at 15:35
3  
@JarrodRoberson: If that's your only argument, why would you force every developer to type 5 unshifted characters to access every instance name, when the languages scoping rules can work for you and you don't have to type anything. I was hoping you'd have some actual data to back up your opinion, but it looks like it's just your own personal dogmatic belief. Apologies if that's not the case, but if it's not can you provide links to support your case? –  Binary Worrier Aug 21 '13 at 14:51

A constructor initializes an object. In other words, when you call the constructor method (function), it sets the instance attributes of the class to what is passed in as the parameters to the constructor as the initial state of the object.

Here's a way to think about it. A class is an idea. An object is the actual thing that the class describes. An analogy would be that the difference between an object and a class is much like the difference between a tree (a physical object with leave and roots and branches) and the idea of a tree (a mix of remembered physical sensations and words that exist in the mind).

In simplest terms, the constructor turns the idea into a thing. The constructor is a static member of the class, which means it belongs to the class (the idea) not the object (the thing) represented by the class.

Now, getters and setters are a completely different topic. To understand them, I would recommend that you review the "public", "private", and "protected" keywords. Any explanation of what getter and setter methods do will make no sense until you understand what these keywords do and why they are in the language. (Hint: The typical use case for Java in the real world is on projects that involve multiple programmers building software in teams. Private and protected members serve to hide complexity from developers who are using classes that have already been compiled and, ideally, documented. When object oriented programming is done well, the resulting classes and objects should have a single, logical pattern of use that can be understood without knowing the details of the implementation.) Once you understand all that, the following will make sense.

A getter is a method that provides read access to a private or protected property (variable).

A setter is a method that provides write access to private or protected property. A setter may include some data filtering capability.

Putting a getter on a class without a setter effectively makes a private or protected property read only to users of the class.

share|improve this answer

Plainly and simply:

  • Constructor: A special "function" within a class that is called every time an object is created (i.e. when you use new). Generally used to initialize the member variables.
  • Getter/Setter: "Functions" (or more correctly: methods) used for manipulating member variables, generally after the object is created from the class. They are just called that because, by convention, their names begin with get (for the methods that return the value of a given member variable) and set (for the methods that allow you to change the value).

These concepts are valid in any object oriented language, not just Java.

share|improve this answer

Class constructors are called just once, when the class is instantiated into a live object. Constructors are typically used to force the new, live object into a known state before anything else can act on it.

For example, if you have a Ball class with a size member variable whenever a new Ball is created the constructor should ensure that size is initialized to some safe value and not some random number. Alternately your Ball constructor can require someone making a new Ball to specify how big a size they want.

Get/Set methods are great for protecting live objects from just anyone poking around and making stupid or dangerous changes. They are also great for allowing your class to do extra work required when some property is change.

For example, your Ball has a setSize(int newSize) so someone can pump it up bigger. This set() function can make sure newSize is a safe value and also do extra work required inside your class like adjust a hidden airPressure member variable used in the hidden ball physics simulation that a user of the class shouldn't have to worry about.

Another example, your Ball has a getMaterialRequired() that returns how much rubber is needed to make a Ball based on what its size is. Someone outside should not know how the Ball knows how much rubber is required, all they need is to know how much. So the get() function both hides the complexity and can do extra work to create results whenever needed.

share|improve this answer
1  
+1 for demonstrating that getters/setters can do extra work and that they're designed to protect data access. –  Eric Hydrick Mar 22 '12 at 18:50

A constructor is simply a special method that instantiates a class.

You can see a class as the virtual equivalent of a real life "cast" used to make pieces in an assembly line -if you could also provide parameters to it- or, more in line with the idea of object orientation, an abstraction. Very much like the concept "person" is an abstraction for every living human being and every human being in relation to "person" is the equivalent of a Java object in relation to its class.

For a given class, you can create a special kind of methods commonly known as "getters" and "setters", although this is not a language construct or even an OO concept. Just a fairly common practice to give access to the contents of the object.

There is much controversy as to whether the use of getters and setters is a good thing; and understandably so, because they effectively expose the class' innards in the interface, breaking the abstraction and encapsulation principles an OO language rest upon.

Many answers for this question, but I hope I was able to give a succinct one with a high information to length ratio. I'm sure there are more in-depth discussions of any of these concepts elsewhere in this site should you be interested.

share|improve this answer
    
+1 for "a succinct one with a high information to length ratio." –  S4M Aug 23 '13 at 21:08

I just wanted to help give an example of how getters/setters might look in some practice

You (presumably) have some sort of credit card. You can adjust your available balance by making new charges or paying money back. You need to see your balance, but you shouldn't be able to just set it to whatever you feel like. We solve this problem by not letting you access your balance directly, but rather through a (i.e. getBalance()). You may want to know how much money you can still charge. The credit card company can also use a getter method to return calculated data. For example, checking your available balance (getAvailableBalance()) could read something like return getTotalCredit() - getBalance();.

Now, you're in college, which isn't permanent. At some point, you'll graduate and move. You need to change your address information with the credit card company. You can't just set your address to anything you want ("Send my bills to this address that corresponds to absolutely nowhere."). You need to update that value, so the credit card company writes some code to update that address. So you have things like setAddress(newAddress). That method may look something like:

if (isRealAddress(newAddress)) {
    address = newAddress;
} else {
    showErrorMessage("You entered an invalid address. Please correct it and try again.");
}

This makes sure that every time you try to change your address, it's to the real thing. You can also use methods to change values without just overwriting them. For instance, with a credit card, you could have methods like:

public String charge(amount) {
    // Can't let you go over your credit limit!
    if (balance + amount > totalCredit) {
        return "DENIED";
    } else {
        balance += amount;
        return "APPROVED";
    }
}
public void pay(amount) {
    balance -= amount;
}

These don't "replace" the old value of a variable like in most setter methods, but they do update the value with checks as needed (like not letting you exceed a credit limit).

share|improve this answer

Just a different approach to explaining it, as different ways work better for different people:

A class is a blueprint to a product (in other words, instructions/measurements on how to build it)

A constructor is the builder of the product. The constructor will build the product according to the given blueprints. When you call the constructor a second time, he will create another product with the same features (unless you tell otherwise).

When you make many products from the same instructions, they will be separate items from each other. Consider two cars of identical model, let's say Ferrari F50. They are both the "same" car, but they will have at least a unique product identification. Let's say the very first will be "Ferrari0001", and the next one will be "Ferrari0002", and so on.

Now, if you want to check which Ferrari you are driving, you might want to check (= get) the product identification from the car engine block. If you have the second F50 that was built, it would display Ferrari0002. In code, this would be done like this: myCar.getIdentification(); and you would then see a different code depending on which car you have (first ever made, second, third... etc).

Let's say you are unhappy with the colour of your car, you need to have it painted (= set). This means the car has now changed, and your local car register may or may not require you to report the new paintjob. Then the system must set your car colour from the original red to something different. They would do it for example: myCar.setColour('black'); Now your car will be otherwise the same as originally, but you changed one property of it. It is still the same car in itself, though.

Hope this helps! For me it took a while to get in terms with OOP after a long procedural history :) Think of everything as a real life "thing".

share|improve this answer

Dr. Frankenstein brings his monster to life.

THAT is what a constructor does. Dr. Frankenstein built his monster (wrote the code), but only when he zaps it to life is he performing the role of a constructor.

Now What?

Dr. Frankenstein keeps the monster locked up in the castle; no one can see him. - There is no method for the angry villagers to get to the monster, never mind actually setting it on fire.

Dr. Frankenstein decides there is money to be made if he lets people see his creation.

Dr. Frankenstein goes on tour with the monster. Buying a ticket to the show is the method by which you get to see the monster. The SPCV (society for the prevention of cruelty to villagers) insists that no one be allowed to actually touch the monster, they can only look at him. This will prevent bad things from happening.

The monster trips on stage and breaks a leg (pun intended). No one is allowed to set the leg except Dr. Frankenstein; after all it's his creation and it is a private affair.

Dr. Frankenstein is offered a tenured position at Moreau Medical School and now needs help maintaining the monster. So now he makes a method that allows the villagers to replace certain parts, like setting in place a new leg. Dr. Frankenstein is nervous and hopes the villagers don't do something stupid like set the monster's leg backwards. But that's a risk he's willing to take.

share|improve this answer

A constructor creates the space in memory that will store your object that you are creating. That would be what a constructor with no arguments does.

Foo f = new Foo();

The constructor can also be written to take arguments, and execute code that will be executed when you create the object. This so you can ensure that the object is in a specific state after it is created, but before it is used.

Foo f = new Foo(1,"abc");

Get and set methods simply wrap members

private Foo _foo;
public Foo Get() { return _foo; }
public void Set(Foo f) { _foo = f; }

This is so you can hide internal state, or do verification before some value is retained. For example a property of type int may need to be between the values of 1 and 10. In your setter you could verify that the value is indeed between 1 and 10, and then take appropriate action if it is not.

private int _volume;
public int GetVolume() { return _volume; }
public void SetVolume(int volume) {
   if (volume < 1 || volume > 10) {
     // take appropriate action
   } else {
     _volume = volume;
}

In summary, they both exist to allow you better control over what a class can and cannot do. Here is a full class that uses both.

class VolumeController {
  public VolumeController(int min, int max) {
    // these don't ever change so set them up in the
    // constructor so once the object is created
    // we always have a valid min and max value
    // for the volume
    _min = min;
    _max = max;
    // default to _min so it is always
    // has a valid value
    _volume = min;
  }

  int _min;
  int _max;


  int _volume;

  public int GetVolume() {
     return _volume;
  }

  public void SetVolume(int value) {
    // here we need to ensure that the volume never
    // gets put in an invalid state
    if (value < min) {
      value = 0;
    } else if (value > max) {
      value = max;
    }
    _volume = value;
  }
}

You should be able to see from the example what a constructor is for, it creates the object and puts it in a valid initial state. The property getter and setter methods allow you to control how a value is set. This class makes it very easy for someone to use your volume controller in an application without worrying if it will throw an exception and break their code. This is the point of both constructors and property setters and getters.

share|improve this answer
1  
why the downvote? –  Charles Lambert Mar 22 '12 at 15:21
    
"A constructor creates the space in memory that will store your object that you are creating." is that really true? –  cartalot Aug 21 '13 at 23:07
    
Simplistically, yes it is true. More accurately, it is allotting a space in memory of the correct size needed to hold all of the data for that instance of the class. It doesn't "create" memeory out of thin air. –  Charles Lambert Aug 22 '13 at 19:03
1  
well yeah - everyone knows it needs to create it out of thick air. thin air is for noobs. –  cartalot Aug 23 '13 at 0:22

Say that you got an idea of your dream house. To be able to build that house you have to create a blue print of it. And that blue print is then used to construct the actual house.

It's the same thing in programming. When you get an idea you formalize it by creating a class. You then use that class to create an object.

So we got this blue print:

class House
{
    void OpenDoor()
    {
    }
}

And to construct the actual house we do:

var myHouse = new House();

But to get a fully functional house we need to provide it with an address, a power grid and a key. (Yes, the house will magically fly to the specified address). Without those things the house would not work properly. Let's modify our class:

class House
{
    private PowerGrid mPowerGrid;
    private Address mAddress;
    private HouseKey mKey;

    bool OpenDoor(HouseKey key)
    {
        if (mKey != key)
            return false;

        //and the logic to open the door here.
    }
}

Now we've specified the required information but we have not initialized it. We could add setters to do that. Like this:

class House
{
    private PowerGrid mPowerGrid;
    private Address mAddress;
    private HouseKey mKey;

    bool OpenDoor(HouseKey key)
    {
        if (mKey != key)
            return false;

        //and the logic to open the door here.
    }

    void setPowerGrid(PowerGrid grid) 
    { 
       mPowerGrid = grid;
    }

    void setKey(HouseKey key) 
    { 
       mKey = key;
    }

    void setAddress(Address address) 
    { 
       mAddress = address;
    }
}

But that solution have to fundemental flaws.

The first flaw is that we now have something called temporal coupling. That is, if we have not called setKey before invoking OpenDoor our code will fail. Because if we have not assigned our own key, how could we verify that the user have the correct key?

The second flaw is that we do not protect our important information. A burglar could just do something like this:

yourHouse.setKey(myBurglarKey);
yourHouse.OpenDoor(myBurglarKey);

And the door to your home would be opened.

If we on the other hand pass all mandatory information through a constructor that would not be possible. We also guarantee that our house have all information which is required to have the house fully functional.

Let's add the constructor instead:

class House
{
    private PowerGrid mPowerGrid;
    private Address mAddress;
    private HouseKey mKey;

    public House(PowerGrid grid, Address address, HouseKey key)
    {
        mPowerGrid = grid;
        mAddress= address;
        mKey= key;
    }

    bool OpenDoor(HouseKey key)
    {
        if (mKey != key)
            return false;

        //and the logic to open the door here.
    }
}

Now we can create our house by passing the information directly. It's also easier to understand what the class requires as it's impossible to create the class without that information.

var myHouse = new House(myCounty.PowerGrid, myAddress, myKey);
myHouse.OpenDoor(myKey);

Summary

All classes have constructuctors. If you have not specified one they get one automatically which takes no parameters. So the first house class really looks like:

class House
{
    public House()
    { 
    }

    void OpenDoor()
    {
    }
}

Getters/Setters is simply methods which is used to access the class fields. Use them with care as they make it easy to break encapsulation by allowing changing the logic of the class from the outside.

For instance, lets say that you would have added getKey(). That you could just have done:

myHouse.OpenDoor(myHouse.getKey());

Not so nice, ehh?

share|improve this answer
    
Minor point: that's not exactly Java. Explanation just as good though. –  Jubbat Aug 22 '13 at 14:55

Constructors and Seters serve the same purpose maintaining invariants. An object has logical properties that must always be true for outside observers ie if player has health greater than zero then isAlive must return true. If player health less than or equal to zero then isAlive should return false, highscore should be recorded for prosperity. Constructors and setters allow an object to control its invariants if you just set attributes directly then outside code might not do everything necessary like forget to record their high score on death or ensure their starting health is greater than zero.

Getters are important for encapsulation if a class left its attributes "open to the public" then change in representation would be impossible. Lets say you have a person class and you want to make birthday and age available outside of the class. Your first implementation you make attributes for both, but latter on you decide it is better to just recalculate age from birthday. If you hadn't hidden both attributes behind getters then this change would be impossible to make without changing all of the code that reads those attributes.

share|improve this answer

Constructors are similar to functions, but they have fixed name same as class name and they are called by new operator during the time of object creation. They are used to initialize instance variables of any class when the object is created. They are called only once.

While on the other hand, get and set methods are specific methods which help any object to access its instance variables through these methods. They provide help in writing code with better encapsulation as now one cannot directly access objects instance variables if they are private but one can access them using these get and set methods. These methods can be called multiple times.

For more info, refer to http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

share|improve this answer

protected by World Engineer Aug 21 '13 at 11:13

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.