Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

classes referring to themselves

Status
Not open for further replies.

davikokar

Technical User
May 13, 2004
523
IT
Hallo,
let's say that I have a class Person that has some attributes like name, partner (another Person), mother (another Person), etc. The class refers to itself and I would write something like this:

Code:
abstract class Person
{
    public String name = "<unknown>";
    private Person father;
    private Person mother;
    private Person partner;
    public Person(String s1) {name = s1;}
}
now I would like to create a method that makes two persons refer to each other, like marriedTo(Person):

I wrote this code:
Code:
	public void marriedTo (Person p1)
	{
		try
		{
			if (this.partner != null || p1.partner != null)
			{
				throw new BigamyException();
			}
			else
			{
				this.partner.name = p1.name;
				p1.partner.name = this.name;
			}
		}
		catch (BigamyException e)
		{
			System.out.println("Illegal marriage");
		}
	}

If I instanciate two persons and make them married I get an a NullPointerException. I don't understand why. Does someone has an hint? thanks
 
Your else statement is executed when this.partner or p1.partner == null. This means that "this.partner.name = p1.name" or "p1.partner.name = this.name" always causes a NullPointerException.
 
I really love the "BigamyException" :)

Did you consider writing a setParner method?



Cheers,
Dian
 
Hi!
Check to see of p1 is null. I don't think you're checking that.
On the other hand, i think you'll have to instanciate the person objects.
And diancecht is right. You should use get and set methods.

On wich object does he get the exception?

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top