Object references (I)

2 March 2008

In this post, I will be talking about how to refer to an object. I will present a simple example to make things obvious.

We have a class called Student. It had 2 attributes, getter setter methods and a method named showAll() to show the contents of both the attributes.

public class Student {
 
	private int id;
	private String name;
 
	public Student(int id, String name) {
		this.id = id;
		this.name = name;
	}
	public Student() {
		// TODO Auto-generated constructor stub
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
 
	public void showAll()
	{
		System.out.println("id: " + id);
		System.out.println("name: " + name);
 
	}
}

So far so good. Now lets do some experiments.

// main method
…
Student obj1 = new Student(1, "Laiq");
 
System.out.println("From main: ");
obj1.showAll();
 
testMe(obj1);
 
System.out.println("From main: ");
obj1.showAll();
…
 
	public static void testMe(Student a)
	{
		System.out.println("From testMe: ");
		a.showAll();
 
		a.setName("Toni");
 
		System.out.println("From testMe: ");
		a.showAll();
 
	}

Output:

From main: 
id: 1
name: Laiq
From testMe: 
id: 1
name: Laiq
From testMe: 
id: 1
name: Toni
From main: 
id: 1
name: Toni

Do read the next posts on this very topic for the comments on the output and for further examples.

del.icio.us:Object references (I)  digg:Object references (I)  spurl:Object references (I)  wists:Object references (I)  simpy:Object references (I)  newsvine:Object references (I)  blinklist:Object references (I)  furl:Object references (I)  reddit:Object references (I)  fark:Object references (I)  blogmarks:Object references (I)  Y!:Object references (I)  smarking:Object references (I)  magnolia:Object references (I)  segnalo:Object references (I)  gifttagging:Object references (I)

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Object references (I)

Leave a Reply