• Advertisement

Archived

This topic is now archived and is closed to further replies.

Simple Java Question

This topic is 5068 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi people I am in the process of learning Java for uni, and I have 3 questions. The first is about get and set methods. I know what they do, but I really dont see the point to them at all...the are just extra repetitive code in your class for no apparent gain. How is saying: someObject.variable = 10; any worse that saying: someObject.setVariable(10); ? Am i missing something here? I take it getters and setters are actually no different than any other method. One other thing, would i be right in saying methods only take parameters in Java if they are getting them from outside the class/object? If you can say in a class:
public int x=10, y=2, area;
aera = calcArea();

public int calcArea()
{
    return (x*y);
}
 
...then I am guessing variables within the class are visible to all the methods within the class... When would you ever need to supply arguments to calcArea? Lastly, if you static methods cant call other methods that are not static, how does main call anything? Probably a stupid question, but like how would you ever call any method that is not static if main is static and everything it calls must be static? Java is difficult to get used to after doing so much C.

Share this post


Link to post
Share on other sites
Advertisement
Hi Mr Lane

Using get and set methods allows you to perform bounds checking and things on your variables.
For example on your setVariable method you may only want to accept positive ints. If this is the case you can then check the argument in the set method before you assign it to the variable. When getting a variable you could make sure that it has been initialized to a valid value before returning it.

As for the funtions taking parameters, with the example that you gave it is unlikely that you would need to pass in any external data. However, if you wanted to increase the size of the shape that you are calculating the area of by an arbitrary amount you could have a method of:

public void increaseSize(int size)
{
x += size;
y += size;
}

This way, you can set any size increase rather than having a preset value in a member variable that you increase by.

Not sure about the last question as I haven''t done much Java.

Hope this helps,

PhilHalf

Share this post


Link to post
Share on other sites
I felt the same way about the get sets, but now i agree.

First you are supposed to put the variable as a private, and have the get sets for it.

second its a design issue, that all java classes follow.
Just to make it "easier". And in a way its easier to track whats going on.

it lets other programmers who would use your classes which values are supposed to be used easily enough, they just look at the gets and sets

java is so class design orientated it will give you a headache.
first you will hate it, then like it, then hate it again, im hating it now, but its what they''re teaching so learn it!

Share this post


Link to post
Share on other sites
Ahh yes I can see this from a design perspective now. And of couse it allows you to keep the variables protected or private. Thanks for the tip.

I also have not done C++. Is C++ as class orientated as Java, or is it somewhere in between C and Java?

Share this post


Link to post
Share on other sites
i havent done c, but c++ i don't believe is as painfully design specific.

But i havent had any teachers teach me the fundamentals in c++, i just learned as a hobby to make games, basically i use c++ for games and java in the future for business,



[edited by - johnnyBravo on April 10, 2004 9:37:25 AM]

Share this post


Link to post
Share on other sites
hmm, considering not to answer knowing what will come out of it.
A big difference between java and C++ regarding objectorientation is that making a good design is much harder in C++ than in Java since you have many more options and can design code pretty much the way you like. This will of course result in poor design by poor designers, in Java on the other hand you have to fiddle around stuff that maybe would be implemented in a better way without OO, like stuff that actually behave as functions.
and BY GOD dont start a java vs C++ battle again.

Share this post


Link to post
Share on other sites
To answer your question about static methods, main() can''t call non-static methods of its class without instantiating first. Then, it can call instance methods of that instance. For example:


public class Example {
public int num() {
return 5;
}

public static void main(String[] args) {
Example e = new Example();

System.out.println(e.num());
}

Share this post


Link to post
Share on other sites
quote:
Original post by Mr Lane
The first is about get and set methods. I know what they do, but I really dont see the point to them at all...the are just extra repetitive code in your class for no apparent gain?



No.

Several important cases:

1. Setters
As well as setting a property, they might also flag it as having changed, or notify any listeners that it has changed, or carry out other actions on the change (as well as bounds checking etc)

2. Getters
Can implement lazy initialisation; something that is got infrequently need not be computed at all until it is got.

However, I do get your point.

IMHO, in cases where you absolutely know that there will never in the future ever be any reason to do any of the above, they can be replaced with public members if performance or size is a real factor (mostly applies to J2ME). Method calls aren''t that slow in Java; the JIT is presumably quite good at inlining trivial getters and setters which means that they take up essentially no more runtime ultimately (obviously they make the JIT itself take a bit longer to run)

If you have Eclipse, try the auto-generation function for getters and setters (takes a lot of the monotony out of it).

Mark

Share this post


Link to post
Share on other sites
Two words
private
synchronized

It''s stupid to add getters and setters to every class without reason, of course you need to do a few design decisions (and know that: if your code coud be abused it would be abused).

Share this post


Link to post
Share on other sites
quote:
Original post by Raghar
It''s stupid to add getters and setters to every class without reason...


The reason would be a good and consequent design and to keep the code OO. Your data should be private and methods should be provided to modify the object, (in almost all cases). Since we talk Java we have to keep our code OO, in C++ on the other hand...

Yes, I know - from a programmers point of view it does suck, writing all those letters and symbols...

Share this post


Link to post
Share on other sites
There are good reasons for the whole using methods/member functions to set/get the values of an object but its not really explained properly or the reasons for them at all and people just think they should be adding get/setters for all attributes just because its OO or something. There are two reasons for setters/getters. One is an object has a state and performs actions, when you design a new type you think about what attributes this type has and the valid range of values these attributes can have, this is called the state invariant, your setters maintain the state invariant keeping the object in a valid state for example think about the type integer it has a state invariant which (depending on platform) is
between -2147483648 to +2147483647. The operations such as assignment which is like a setter maintain this state, never puts it above or below which would be illegal.

I got a better example, lets design a new type called "ByteBuffer" which is just a container of byte values you can fill regions in for buffering. The attributes i think this type has are:

byte buffer[]
int capacity,
int limit,
int position,
int mark;

the state invariant for this type is:

Invariants: mark <= position <= limit <= capacity

The only way i can maintain this state invariant is through the operations i give this type, thats why your told its best to make attributes private because if it wasn''t it would be easy to put the object of that type in an invalid state
and may cause undefined behaviour. So lets give it an operation that shows an example of maintaining a valid state call it "get" which is just a getter:

public byte get(int index) throws out_of_range {
if ((index < 0) || index >= _limit){
throw new out_of_range("Index out of bounds");
}
return buffer[index];
}

So there you go, the object will never be in an invalid state and not cause undefined/unexpected behaviour and makes finding bugs easier to find.

The other reason for making attributes private is do with module coupling, some types can have more than one data representation, at some point you may decide to change its representation and if you allowed direct access to it in other modules you''ll have to update everything to reflect this change, imagine if another team was using your module bad news this is known as "tight coupling".

Well this is where "Abstract Data Types" ADTs come in, you design a new type by describing its operations regardless of what data representation to use thus creating an "interface" between that new type and other modules using it that almost never changes. You can always change its data representation and you''ll almost never need to update everything else your creating a "loose coupling" which is good. The best example of that is java''s List type, its an interface has no data representation it only describes it operations which is the only thing you need to be concerned about, people passing around List could use arrays, single/double link list to represent it but thats no concern of anyone.

The thing about the keyword static in all languages have different meanings depending on there context, like in C i think when you declare a function prototype static it just means it becomes private in that module scope you can''t use in another file, when you declare a variable static in a function defination it persists through out all invocations, in C++ its used for other meanings aswell. In java when you flag a class attributes/methods static you do not need to create an instance of that class to use it but if you want to use a non static method inside a static one there needs to be a instance of that class in there to use that operation.

I hope that makes abit more sense i''m not very good at explaining things well.

Share this post


Link to post
Share on other sites

  • Advertisement