defining a constructor class and initialising values - java

I'm stuck on a homework question which asks me to define a constructor for class Jar which initialises the variable position to 0 and the variable stone to null. Was just wondering if the code I did below is the right way to do this? Also am I able to initialise the values used in this constructor in a different class?
public class Jar
{
public int position;
public Jar stone;
public Jar()
{
position = 0;
stone = null;
}
}

Was just wondering if the code I did below is the right way to do this?
Yes, although:
As Stultuske points out, those are the default values that the fields will get even if you don't assign anything to them, so the constructor isn't necessary. But if the assignment said to write one...
I always advise being explicit:
this.position = 0;
this.stone = null;
Java allows you to leave off the this. part, but I wouldn't.

Related

How to properly declare static variables in android?

I have a dilemma because I don't know what is better solution. I have a static variable.
I wonder what is the best practice of declaring these variables.
Let's suppose that I have such a variable in myStatic class.
public class myStatic(){
public static int integer = 0;
/* get value */
public int getInteger() {
return integer;
}
/* set value */
public void setInteger(int nInteger) {
integer = nInteger;
}
}
Now I must increment this variables or decrements.
How to do it correctly?
1)
myStatic.integer++;
2)
myStatic mystatic = new myStatic();
int integer = mystatic.getInteger();
int nInteger = integer+1;
mystatic.setInteger(iInteger);
Is better using solution 1 or 2?
I would go with number 1, 100%, maybe just because I'm lazy, but kind of also because of:
Don't repeat yourself
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
Keep it simple, stupid
This principle has been a key, and a huge success in my years of software engineering. A common problem among software engineers and developers today is that they tend to over complicate problems.
You aren't gonna need it
Principle of extreme programming (XP) that states a programmer should not add functionality until deemed necessary.
If that variable needs to be accessed everywhere and at any time, you should go with option 1.
It will act as an Environment variable even tho its not reallyyyy the same thing.
more info on env vars:
https://en.wikipedia.org/wiki/Environment_variable
Static variables need not be accessed through an object. Infact it is a waste of code.
Consider this :
public class MyStatic {
public static int i = 0;
}
You can directly access the static variable like this :
private MyStatic myStatic = null;
myStatic.i++;
This is because, the JVM doesn't even care about the object for a static property.
since static vars are class variables, they can be manipulated by any object, unless you declare a static variable as private, you had to access to it via public static methods. Then, your first approach is correct, in the second the method getInteger() does not work.
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
I recomend you to read about the singleton pattern design.

How to access a private method

private void generateActionPerformed(java.awt.event.ActionEvent evt) {
String number = getRandom(4);
int first,second,third,forth;
first = Integer.parseInt(number.substring(0,1));
second = Integer.parseInt(number.substring(1,2));
third = Integer.parseInt(number.substring(2,3));
forth = Integer.parseInt(number.substring(3));
}
private void reavealActionPerformed(java.awt.event.ActionEvent evt) {
}
so, i have for integer that i want to use it in the bottom method. Is there a way to carry(the same value) for integer first,second,third,forth into the bottom method(reavealActionPerformed) from the top method?
thank you
Nope. Please read up on variable scoping in Java. (More detailed explanation of scoping - http://www.java-made-easy.com/variable-scope.html )
In short, anything declared within a method (public/private/protected), is not available outside the method. More technically, the scope of the variable is the block where it is declared, including any sub block.
If you want to share the values, think about whether they can be part of your class. If they are logically your class' attributes, you can define them as instance variables.
Or you can try returning the values in an array and call this method when you need and the values will be 'returned' from the method.

What's the point of get and set methods [duplicate]

This question already has answers here:
Set and Get Methods in java?
(16 answers)
Closed 8 years ago.
In my CS class I am just learning about classes and OOP.
So when you create a class you initialize a certain number of private variable.
I know you make them private because if they were public they would be easily changeable and could lead to a lot of bugs.
So we use get and set methods to change the variable. But that once again makes the variables very easy to change right? So whats the point of making them private in the first place?
Some benefits of using getters and setters (known as encapsulation or data-hiding):
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.
As the above comment states, getters and setters encapsulate (i.e. hide) inner details of your class. Thus other classes that interact with yours, do not need to know about the implementation details.
For example, in the simple case you describe, instance variables are exposed via getters and setters. But what if you wanted to change your class so that you no longer used instance variables, but rather you persisted the values to disk. You could make this change to your class without affecting the users of your class.
Keep in mind also that getters and setters need not always be provided. If you do not want your class to provide a way to set or read these properties, then don't. Simply make them private.
get is used to obtain a value for an attribute and set is used to put a value to an attribute
ex:
private int variable;
public int getVariable(){
return variable;
}
public void setVariable(int aux){
variable=aux;
}
In general, is used to encapsulate an attribute.
reference:
Set and Get Methods in java?
Encapsulation or data hiding gives u more control on what values can be set to a field. Here is an example if you don't want a class attribute to have a negative value:
class WithoutGetterSetter {
public int age;
}
class WithGetterSetter {
private int age;
public setAge(int age) {
if(age < 0)
// don't set the value
else
this.age = age;
}
}
public class testEncapslation {
public static void main(String args[]) {
WithoutGetterSetter withoutGetterSetter = new WithoutGetterSetter();
withoutGetterSetter.age = -5;
WithGetterSetter withGetterSetter = new WithGetterSetter();
withGetterSetter.setAge(-5);
}
}
Get and Set methods are preferable to "public" variables because they insulate the users of a class from internal changes.
Supposing you have a variable "StockQty" and you made it public because that seemed like the easiest thing to do.
Later on you get a user requirement to track the history of stock over time. You now need to implement a SetStockQty() method so you can save the old quantity somewhere before setting the new quantity.
Now all the users of your class have to change there code, re-document and re-test.
If you had SetStockQty() method to begin with only you would need to change and test your code.
The second reason is you can have Getters without Setters effectivly making the variable "read only".
Traditionally, they are justified in terms of encapsulation. By providing moderated access to read and write the fields of a class, we supposedly reduce coupling.
In simpler language: by controlling the ways in which other classes can read and change our data, we reduce the ways in which our class's data can change. This means that the connections between classes are reduced, which reduces complexity.
However, the same logic says that getters and setters should generally be avoided unless there's an actual need for them, and there very seldom is such a need. For the most part, a class should "tend to its own knitting" - if there's a calculation to be done on this class's data, it should do it. If a value should be changed, it should do the changing.
For example, consider an object in space. It has a location specified as (x,y,z). We could possibly allow other classes to just set those arbitrarily - this would be horrible, obviously, but it's not obvious that a setter for these would be any better. What you really want is a constructor to set an initial position, and then methods to influence that position - for example, to register an impact or an acceleration. Then you're doing OO programming.
One word, Encapsulation.setters also allow you to control how values are entered into your program. Many new programmers like myself are often confused by this concept. I strongly advice you read this SO question
Being objective: it's all about best pratices!!!
1) IF necessary, expose your attributes with get methods.
2) IF necessary, allow attribute modification (state modification) using set methods;
Have both public get and set methods without treatment is the same as have the attributes public.

How to create a copy of an instance without having access to private variables

Im having a bit of a problem. Let me show you the code first:
public class Direction {
private CircularList xSpeed, zSpeed;
private int[] dirSquare = {-1, 0, 1, 0};
public Direction(int xSpeed, int zSpeed){
this.xSpeed = new CircularList(dirSquare, xSpeed);
this.zSpeed = new CircularList(dirSquare, zSpeed);
}
public Direction(Point dirs){
this(dirs.x, dirs.y);
}
public void shiftLeft(){
xSpeed.shiftLeft();
zSpeed.shiftRight();
}
public void shiftRight(){
xSpeed.shiftRight();
zSpeed.shiftLeft();
}
public int getXSpeed(){
return this.xSpeed.currentValue();
}
public int getZSpeed(){
return this.zSpeed.currentValue();
}
}
Now lets say i have an instance of Direction:
Direction dir = new Direction(0, 0);
As you can see in the code of Direction, the arguments fed to the constructor, are passed directly to some other class. One cannot be sure if they stay the same because methods shiftRight() and shiftLeft could have been called, which changes thos numbers.
My question is, how do i create a completely new instance of Direction, that is basically copy(not by reference) of dir?
The only way i see it, is to create public methods in both CircularList and Direction that return the variables needed to create a copy of the instance, but this solution seems really dirty since those numbers are not supposed to be touched after beeing fed to the constructor, and therefore they are private.
EDIT1:
CircularList is a class that is a looped around version of ArrayList. You can see that i feed it an array called dirSquare and then a number. The number is an index in that array. So if the number i feed it is for example 3, it will be the last element in dirSquare, which has value of 0. When i use shiftRight and shiftLeft, the index gets incremented/decremented and if i increment pass the size of the last element of the array, it loops around and starts with 0th elemnt. The same thing happens if i go pass 0 on the other side. Thats why its called Circular list. I cant use getXSpeed/getZSpeed because they return the value of the array. I need the index, which is strictly an implementation variable.
A common way to go about this, is to create a copy constructor. An example can be found here
Another solution would be to implement the Cloneable interface, but most developers recommend against it, including Joshua Bloch in Effective Java, calling Java's clone "deeply broken".
Why not add another constructor taking a Direction parameter. Something like:
public Direction(Direction source) {
this(source.xSpeed, source.ZSpeed);
}
I'd add a private/protected constructor without arguments, so you can initialize each member with its own copy (with your constructor it seems you'll have a reference inside your CircularLists, so you need to inizialize them manually inside clone method).
Edited
public Direction() {};
public Direction Clone() {
Direction dir = new Direction();
dir.diSquare=this.dirSquare;
for each elem in xSpeed
dir.xSpeed.Add(elem)
for each elem in zSpeed
dir.zSpeed.Add(elem)
return dir;
}

Object in Object Array doesn't want to store my data

fairly new to this language. Long time lurker, first time question asker.
In my program, I load a bunch of strings from a text file and then pass all of that information inside of a String array to a program that takes the data point by point (it comes in a reliable pattern) and assigns it to variables inside a class.
I use this loop to create the objects.
Gladiator[] gladiator = new Gladiator[(match.contestants)];
for ( int a = 0; a < match.contestants; a++) {
gladiator[a] = new Gladiator();
gladiator[a].populategladiators(parsedInfo,a);
}
Gladiator class full of public final variables which are defined in the method populategladiators. The syntax is as follows:
this.name = parsedInfo[0+mod][0];
this.culture = parsedInfo[1+mod][0];
this.background = parsedInfo[2+mod][0];
etc.
At the moment, I only load two gladiators and it seems like maybe both are being set at once with both pass throughs? Anyone have any thoughts on this?
Also, in another method in class Gladiator, should I be able to call this.name and be okay to get data about the object I specified when calling the method?
Edit: Trying to make the code look right. Giving up since there isn't much.
2nd Edit: Example of variable declaration in gladiator class:
public static String name;
public static String culture;
public static String background;
I had my variables set as static, thus it wasn't allowing me to set individual variables for the objects. I just didn't understand what the static keyword meant.

Categories