1,105,427 Community Members

get/set Methods in java

Member Avatar
Maureen
Newbie Poster
4 posts since Nov 2004
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I am new to programming, so please accept my apologies if this question is simple.

I have a class (say called Student).
I want to store the name of the student (name) and the course (course)

I have declared some variables in my Student class:

private String name = " ";    //Holds the data for name
        private String course = " ";  //Holds the data for course

I have declared a constructor for my Student class:

Student (String studentName, String studentCourse)
        {
            name = studentName;
            course = studentCourse;
        }//end constructor Student

I have declared some methods in my Student class:

//This method returns a String with the contents of the variable 
//name to whatever object calls it
        public String getName ( )
        {
            return name;
        }//end method getName

//This method allows the contents of name to be changed 
//to store a different String value, should that be required
        public void setName (String studentName)
        {
            name = studentName;           
        }//end method setName

        public String getCourse ( )
        {
            return course;
        }//end method getCourse

        public void setCourse (String studentCourse)
        {
            course = studentCourse;
        }//end method setCourse

In another method called hashCode, I change the name varable in my Student class to upperCase i.e.

public int hashCode (int numStudents)
        {
             int hash = 0;
             int subtotal = 0;
             int maxNum = 0;

            //Convert name to upper case
            name = name.toUpperCase ( );

And then use the upper case name variable to calculate my hash code.

What I would like to know is this the best way of doing things? Or should I be using the setName method to change the name variable to upper case?

Also, does anyone know of any online resources where I can look at the set/get methods? (My course notes are very limited).

Thanking you in advance.

Member Avatar
Narue
Bad Cop
12,139 posts since Sep 2004
Reputation Points: 5,693 [?]
Q&As Helped to Solve: 1,537 [?]
Skill Endorsements: 81 [?]
Team Colleague
 
0
 

get/set methods should be used judiciously. As it is, you could simply make your members public, remove the get/set methods, and the effect would be the same with less code.

Member Avatar
jerbo
Junior Poster in Training
84 posts since Sep 2004
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

AS Narue says, use get/set judiciously. The greatest power of Java (and any OO programming language that is,) is the ability to 'encapsulate' data (members) to better control how to use that data.

A good example in your above code is if you wish to make the course member 'read-only' you can exclude the set method. This would prevent anyone from making unwanted changes to the course member data. You can still set the course member data internally to the class, but not outside the class (since it would still be a private member variable.)

Member Avatar
Maureen
Newbie Poster
4 posts since Nov 2004
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
1
 

Thank you for your reply Jerbo and Narue.

Did some research and found the following:

accessor methods
Normally you don't make variables in your class public. Instead you provide public set and get methods for the variable. This lets you then later change the way the variable is stored, or add extra validation checks.

Method names made up of a member name with a get or set prefix are methods that are required when the members are private and therefore cannot be accessed from outside the class (which is good programming I understand). Any program that creates instances of a class will use these methods to access the members. A member does not need a set method when its value is changed in other methods.

The get/set methods are not compulsory, only include them for members when other classes require access to them.

The get methods (also called an accessor method) return the value of the member they are associated with and the set method (also called a mutator method) sets the member to a new value.

Using get and set methods aids maintainability, flexibility and extensibility. Good design includes encapsulation – to do this you make public asscessor methods and force calling code to use those methods. I.e. set and get

ohyeah
Light Poster
48 posts since Aug 2005
Reputation Points: 0 [?]
Q&As Helped to Solve: 2 [?]
Skill Endorsements: 0 [?]
Unverified Member
 
0
 

brilliant

Member Avatar
sandwiches99
Newbie Poster
2 posts since Nov 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

get/set methods should be used judiciously. As it is, you could simply make your members public, remove the get/set methods, and the effect would be the same with less code.

I know I'm 4 years late, but I found this page... I forget what I googled to find it. Direct assignment is easy, but unless you want absolutely any values to be accepted, mutator methods should be used to handle values that could otherwise cause errors at some point in your code. It's just good practice, it makes your code more robust, and it just makes sense in OOP.

Member Avatar
stultuske
Posting Expert
5,325 posts since Jan 2007
Reputation Points: 938 [?]
Q&As Helped to Solve: 776 [?]
Skill Endorsements: 35 [?]
Featured
 
0
 

brilliant

that you can't read dates? mwa, not so astonishing.

about Sandwiches99, if you know you're 4 years late... why still post?

Member Avatar
sandwiches99
Newbie Poster
2 posts since Nov 2008
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
1
 

that you can't read dates? mwa, not so astonishing.

about Sandwiches99, if you know you're 4 years late... why still post?

Just putting in my 2 cents. And I love you.

Member Avatar
stultuske
Posting Expert
5,325 posts since Jan 2007
Reputation Points: 938 [?]
Q&As Helped to Solve: 776 [?]
Skill Endorsements: 35 [?]
Featured
 
0
 

JAnd I love you.

you consider that to be Java related? :D

Member Avatar
Piachen
Newbie Poster
1 post since Nov 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Just putting in my 2 cents. And I love you.

Eventhough something happend years ago, there will always be peoply just starting with programming and experiencing the same issues - like myself for example. So I don't care that something is written with 4 years in between. I'm just happy to find something that might help me further on.

Member Avatar
nalle
Newbie Poster
1 post since Jan 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-1
 
public class Pearson  {
       private String name;

// likely a setter somewhere in here 
// your getter method here
           }
Member Avatar
stultuske
Posting Expert
5,325 posts since Jan 2007
Reputation Points: 938 [?]
Q&As Helped to Solve: 776 [?]
Skill Endorsements: 35 [?]
Featured
 
0
 

ehm... yup, that's bout it ...
except: I don't see a getter, I don't see a setter and I don't see an explanation or a question in your post.
if you have a question about it, it's easier for us to answer it if we know you have a question and if we know what that question is.

Member Avatar
fardoonmuhafiz
Light Poster
27 posts since Jan 2010
Reputation Points: -11 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
0
 

The best way of programming is to make your fields(member variables) always private and make your methods public to preserve encapsulation in java. The setter(mutators) and getter(accessors) methods are used to set and get the field values by other classes. you can directly use yourobject.hashCode() to find the hash code.

Member Avatar
thundervortex
Newbie Poster
1 post since Jan 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Eventhough something happend years ago, there will always be peoply just starting with programming and experiencing the same issues - like myself for example. So I don't care that something is written with 4 years in between. I'm just happy to find something that might help me further on.

I constantly refer to outdated posts to get responses that are more specific than the topic I am looking for. Just to further emphasize, here I am months after this 4year comment is made, and I just learned something from this discussion thread. Why start another thread, when pertinent information may be already posted here. Thanks for appending to this thread, some of us greatly appreciate the additional and current updates to a thread!

Member Avatar
samdutton
Newbie Poster
1 post since Feb 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

>> about Sandwiches99, if you know you're 4 years late... why still post? <<

Sorry to add to the noise, but sandwiches99 makes a sensible comment -- so why is there a problem that it's four years after the OP?

I only just found this thread, and it's 2010! (It didn't answer my question, but that's another problem...)

Member Avatar
BestJewSinceJC
Posting Maven
2,760 posts since Sep 2008
Reputation Points: 700 [?]
Q&As Helped to Solve: 366 [?]
Skill Endorsements: 17 [?]
 
0
 

And neither of you guys think it is fishy that nobody with over 10 posts on this forum cares? But that two people with one post each happen to come in this thread and co-sign? Fooled us.

Member Avatar
TechnoWizard
Newbie Poster
3 posts since Apr 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

get/set methods should be used judiciously. As it is, you could simply make your members public, remove the get/set methods, and the effect would be the same with less code.

Unless this is already well known from you programmers, removing the get/set methods and making variables public would defeat the purpose of 'Object-Oriented' Programming.

"Just because you can do it doesn't mean you should"
~ Trey Nash(Escalation Engineer, specializing in C/C++/ATL/C#)

If you don't care about Object-Oriented Programming, then I am guessing you aren't looking for any future advancements or careers involving the subject, and/or you are going to have more miserable confusing messes to debug when attempting to run.

Member Avatar
jwenting
duckman
8,359 posts since Nov 2004
Reputation Points: 1,399 [?]
Q&As Helped to Solve: 447 [?]
Skill Endorsements: 35 [?]
Infraction Points: 5
Team Colleague
 
0
 

Unless this is already well known from you programmers, removing the get/set methods and making variables public would defeat the purpose of 'Object-Oriented' Programming.

not necessarilly, but you would need a good explanation as to the why of the omission to convince me of it being a good design decision.

For example when creating something where the extra overhead (call stack creation...) of using getters and setters would yield unacceptable performance (think a raytracer or 3D animation package) you might want to have some class members in the core of that system that are called at extremely high rate to be publicly accessible.

Member Avatar
TechnoWizard
Newbie Poster
3 posts since Apr 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I have helped assemble the XNA Game studio library source code in C#. The only time I saw public variables were when new structures were being created. Of course in java there isn't such a thing as structs and so it is classes. Now variables in this case can be public but more only if the class is intended on being a 'variable' type class ~ Such as a Vector Class (in 3D) that would have 4 public float values of X, Y, Z, & W.
If you need to access a specific variable(s) from class(s) through another class WITHOUT using get/set methods, you can simply implement it.

public Class A{
          private String sA = "This is class A.";
}

public Class B implements A {
          private String sB = "This is class B.";
          public String toString(){// get method
                    String out = String.format("Class A's value: %s, Class B's value: %s", this.sA, this.sB);
                    this.sA = "Class A's String value changed to this...";
                    out += String.format("Class A's new value: %s", this.sA);
                    return out;
           }
}

public Class Main(String[] args){
           B b = new B()
           System.out.println(b.toString());
}

In summary, if you need to use a variable from another class - implement that class, otherwise create your own 'Variable' class that will hold values. Such in XNA(C#) as:

public struct Vertex4{ // or class in java
          public float X;
          public float Y;
          public float Z;
          public float W;
}

Not only will this be good Object-Orientation but it will also be easier to debug later on.

Aside from this, also thought that this might be helpful as well...
you have created a new instance of a class but want to access it from 2 other classes, what do you do?
PASS IT ON!

public class A{ 
        // anything without a beginning is automatically assumed private
        float number = 1.5f;
        // some alteration code to alter number

        public float getThisFloat(){
                 return number;
        }

        public  void setThisFloat(float value){
                 number = value
        }
}

public class B{
       A a;
       B(A a){
                 this.a = a;
       }

       float newNumber;
       public void editNumber(){
                 // do something with number
       }
}

public static void Main(String[] args){
       A a = new A();
       B b = new B(a); 
       // this way you don't have to create a new instance of A
       // and you can be able to access all the current public values of A
}
Member Avatar
BestJewSinceJC
Posting Maven
2,760 posts since Sep 2008
Reputation Points: 700 [?]
Q&As Helped to Solve: 366 [?]
Skill Endorsements: 17 [?]
 
0
 

Most everything you said above is wrong. You can only implement interfaces not other classes. You can extend other classes in an inheritance hierarchy. Or if you want access to another classes public members you can simply instantiate a new Object of that classtype and then say object.variable

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article