r/javaexamples • • Dec 15 '18

Two more common Java problems (hiding, for-each changes)

1. inadvertent hiding

You make a ball that you move around on the screen:

class Ball {
    int x, y, width, height;
    int xspeed = 3; //in pixels
    int yspeed = 3;
    
    Ball() {
       x=100;
       y=100;
       ...
    }

    void move() { ... }
} 

Later on you want to make it collide with another ball or some object, so you make it a Rectangle which lets you use the Rectangle class method .intersects()

class Ball extends Rectangle {
    int x, y;
    int xspeed = 3; //in pixels
    ...

Problem
The Rectangle's x,y,width,height, variables are hidden by the variables in this subclass. Thus .intersects() will never work.

Solution
Delete the line int x, y, width, height; so that when you set values for these variables, you're setting the Rectangle class values


2. Changing objects in a for-each loop

Consider the code below: It creates 5 items, tries to change them, and then prints them out.

NOTE
When using a for-each loop, you can change the property of an item in the loop, but you cannot change the item itself. I don't know why this is. If you want to change the item itself, you have to use a regular for loop with .get() and .put().
You can change the name of item 3, but you cannot change the whole item 2 to be recreated with 99.

import java.util.ArrayList;

public class ForEach {

	public static void main(String[] args) {
		ArrayList<Item> items = new ArrayList<Item>();
		//create items
		for (int i = 0; i < 5; i++) {
			items.add(new Item(i));
		}
		//try and modify using for each loop
		for (Item z : items) {
			if (z.n == 2) z = new Item(99);
			if (z.n == 3) z.name = "Three";			
		}
		//print items
		for (Item z : items) {
			System.out.println(z.n + "=" + z.name);
		}
	}
	
	static class Item {
		String name = "blank";
		int n;

		Item(int n) {
		     this.n=n;
		} 
	}

}

/* Printout:
	0=blank
	1=blank
	2=blank
	3=Three
	4=blank
*/
2 Upvotes

1 comment sorted by

1

u/-bobby_newmark- Jan 24 '19

Try to call a setter method in foreach loop. You'll be surprised