Why encapsulation is good for interchangeability and working in team? - encapsulation

That's my question.
Thank you!

Encapsulation is good because you can protect the values of variables and what variables can be seen/edited.
Here's an example in Java:
public class Foo {
private int size;
private String name;
public int getSize() {
return size;
}
public void setSize(int size) {
if (size > 0)
this.size = size;
}
public String getName() {
return name;
}
public void setName(String name) {
if (name == null || name.isEmpty())
return;
this.name = name;
}
}
This makes sure that the variable size is greater than 0 and the value of name isn't empty or null. You can also put checks in the constructor.
One more thing. If you had made the variable size public, and everyone used fooObject.size=232, and then suddenly you wanted to make restrictions, it would break everybody's code. It's better just to start by using encapsulation.
Hope this helps :)

Related

Generic methods java for Character and String

I'm looking for a quick solution about an issue in my following code. It is working but not how I wanted.
So,
the idea is that I'm trying to pass an Character class array and convert it into ArrayList. Since I'm using generics, I specified:
public void fromArrayToCollection(T[] a,Collection e)
and I guess this means I can pass what kind of arrays I want, such as Int array, char array,String array,double and so on
But it won't let me pass an character array.
If I am passing a String array is it actually working
Why?
Thank you.
public class FuDaBi {
static class StringToArray{
public <T> void fromArrayToCollection(T[] a,Collection<T> e)
{
for(T x: a)
e.add(x);
}
public <T> void fromStringToArray(T inputString, T[] array )
{
}
}
public static void main(String[] args)
{
Character[] my_array = {'S','A','L','U','T'};
ArrayList<String> result = new ArrayList<String>();
String daniel[] = {"WV","Mercedes"};
StringToArray myimp = new StringToArray();
myimp.fromArrayToCollection(daniel,result);
for(int i=0;i<result.size();i++)
{
System.out.println(result.get(i));
}
}
}
The problem is that I made the ArrayList a String type instead of an Character.
ArrayList result = new ArrayList();

array required, but java.lang.String found card game

I'm making a deck and card class for a game, and have encountered an error in creating and using a string array.
my code looks like this: The error is 4 lines from the bottom where it says String undealt = ... undealt[0] and it says "array required, but java.lang.String found" and now I am confused
import java.util.*;
public class Deck
{
private static int currentCard = 0;
public ArrayList<Card> deck;
private String rank;
private String suit;
private String[] undealt = new String[52];
Deck(String[] ranks, String[] suits, int[] values)
{
for(int i = 1; i <= suits.length; i++)
{
for(int x = 0; x < ranks.length; x++)
{
Card card = new Card(ranks[x], suits[i], values[x]);
deck.add(card);
}
}
shuffle();
}
public String toString()
{
String undealt = "Undealt cards:\n" + undealt[0] + undealt[1] ...;
for(int i = currentCard; i < deck.size(); i++)
{
int g = i - currentCard;
undealt[g] = deck.get(i).toString();
}
}
The problem which you are having derives from these lines in your code:
private String[] undealt = new String[52];
:
:
public String toString() {
String undealt = "Undealt cards:\n" + undealt[0] + undealt[1] ...;
:
:
}
As you can see, you have defined the variable undealt in two different scopes. The first declaration is at the instance level, where you have declared undealt to be an instance field of type String[]. The scope of an instance variable is the entire class in which it is defined, i.e. an instance variable can be accessed by all methods in that class.
The second declaration is at the local block level, where you have declared undealt to be a local variable of type String. The scope of a local variable is limited to the block in which it is declared (blocks are delimited by curly braces).
As you can see, undealt is in scope twice in the method toString(), once as an instance field, the second time as a local variable. The compiler has rules which it uses to resolve variable names when they conflict in this way, and will use the local variable definition. This is called "hiding" the instance field, i.e. the local variable hides the instance field.
When the compiler tries to compile...
String undealt = "Undealt cards:\n" + undealt[0] + undealt[1] ...;
it determines that String[] undealt is hidden, and it will resolve undealt as type String.
Therefore, when you attempt to use the array element access operator (the brackets after the variable name), the compiler gives you an error. It has determined that undealt is a local String and therefore it does not have any array elements to access.
A good practice is to avoid ever using two variables with the same name in order to avoid potential sources of confusion such as this. The compiler has a set of rules to use to resolve variable accesses in the case of a conflict, but these needn't be obvious to programmers and can cause confusion.

Combination of String array and Radom

I want to have an array which randomly gives me one of the given answers. But Java says "array[hallo] not possible; you use String but int is expected"
Is there a possibility to solve this problem or am I all wrong?
import java.util.Random;
public class ZufallsAntworten
{
private Random ran;
public ZufallsAntworten()
{
ran = new Random();
}
public int richtigeAntwort()
{
String[]array = new String[100];
array[0]="a";
array[1]="b";
array[2]="c";
array[3]="d";
int hallo = ran.nextInt(array.length+1);
return array[hallo];
}
}
Your method richtigeAntwort() returns an int, but you are returning a String, since your array is an array of Strings. This line:
return array[hallo];
will fetches one of the Strings from your array at that index and return it.
I cannot read the name of your method so I cannot advice you much beyond simply changing the return type of the richtigeAntwort() method to String.

Updating an Array that belongs to one class from another class

I'm wrote this code a long time ago and thought I understood it at that time but now I'm trying to wrap my head around how it works...
// Main.as
package {
public class Main {
public function Main() {
var fruit:Array = [];
UpdateClass.update(fruit);
trace(fruit); // Traces out the string pushed into it? How??? I think the data would've got lost...
}
}
}
// UpdateClass.as
package {
public class UpdateClass {
public static function update(array:Array):void {
array.push("haha, this is not a fruit!");
}
}
}
I just don't understand how the UpdateClass manages to update Main's fruit array? I'm thinking the data would get lost because it is not returning the new array?... When I try this with Strings and Numbers the data does get lost like expected.
I don't know what I was on when I wrote this but I would like to try and understand the logic behind this.
Thank you.
String and Number are "primitive" data types in AS3, while Array and other objects like MovieClip are "complex" or "reference" data types.
When you pass a primitive, its value is copied, so modifying that doesn't affect the original. When you pass a complex object, it's actually a reference to the object's address in memory, so your function is modifying the original object.
I'm assuming something like following when you say that the value was lost with String and Number:
// UpdateClass.as
package {
public class UpdateClass {
public static function update(num:Number):void {
num = 1;
}
}
}
The reason it was lost was because you got a reference to the original object as num. But the function update changed that reference to another Number object which contained the value '1'. This would be true for array too, if you assign another array to the passed reference like:
// UpdateClass.as
package {
public class UpdateClass {
public static function update(array:Array):void {
array = new Array();
array.push("haha, this is not a fruit!");
}
}
}
But, since you are just calling a method on the passed reference (push), 'array' still refers to the original Array and updates it.

class to return an object array with member attributes that can be accessed from main class

I'm new to Java, so the concepts and terminology are fuzzy, but I'm trying! I need to create a class that will take data in a string, parse it and return an object (array) with member attributes that can be accessed from the main class. I've read that this is a better solution than having multiple indexed arrays like pointx[], pointy[], pointz[], etc.., especially if you need to perform operations like swapping or sorting.
So, I'd like to access the array object's members from main with something like test[0].x, test[100].y, etc. however, I'm frustratingly getting an Exception in thread "main" java.lang.NullPointerException and I don't understand how to proceed.
Here's how I'm calling parse from main:
parse a = new parse();
parse[] test = a.convert("1 2 3 4 1 2 3 4 1 2 3 4"); // <- ** error here **
System.out.printf("%.2f %.2f %.2f %d\n", test[0].x, test[0].y, test[0].z, test[0].r);
Here's the parse class:
public class parse {
parse[] point = new parse[1000];
public float x;
public float y;
public float z;
public int r;
parse() {
}
public parse[] convert(String vertices) {
// parse string vertices -> object
point[0].x = 10; // <- ** error here **
point[0].y = 100;
point[0].z = 50;
point[0].r = 5;
return point;
}
}
Thanks in advance for any help specifically with my parse class & any related java pointers to continue my learning java and enjoyment of programming!
When you create an array of parse objects the array itself is empty and doesn't actually contain any objects, only null references. You also need to create the objects themselves and store them in the array.
Furthermore, your point is a member of your parse class when it should be a local variable of your convert method, which itself should be static, since it doesn't rely on a particular instance.
You would then invoke the conversion as follows:
parse[] test = parse.convert("this string not used yet");
System.out.printf("%.2f %.2f %.2f %d\n", test[0].x, test[0].y, test[0].z, test[0].r);
Here's the parse class:
public class parse {
public float x;
public float y;
public float z;
public int r;
parse() {
}
public static parse[] convert(String vertices) {
// parse string vertices -> object
parse[] point = new parse[1000];
point[0] = new parse();
point[0].x = 10;
point[0].y = 100;
point[0].z = 50;
point[0].r = 5;
return point;
}
}

Resources