Hi, I'm quite new to java, and I've come to the point where there are just some things that I don't get no matter where I look or what I read up.
I've been confused with using a created class as a variable type for quite some time now. Take this class for example:
public class Dragon { private String name; private boolean breathesFire; public Dragon(String name, boolean breathesFire) { this.name = name; this.breathesFire = breathesFire; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isBreathesFire() { return breathesFire; } public void setBreathesFire(boolean breathesFire) { this.breathesFire = breathesFire; } }
This was provided by my lecturer. In another class, he has done this:
package com1003.objectville.composition; public class Knight { private String name; [B]private Dragon dragon;[/B] public Knight(String name) { this.name = name; } public Knight(String name, Dragon dragon) { this.name = name; this.dragon = dragon; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Dragon getDragon() { return dragon; } public void setDragon(Dragon dragon) { this.dragon = dragon; } public String toString() { String s = "Knight: "+name; if (dragon != null) { s += ", his dragon is: "+dragon.getName(); } return s; } }
Now I've made my area of concern in bold above. You see how he makes the private variable "dragon" type "Dragon"? So he wrote "private Dragon dragon" instead of "private int dragon" or something that I usually see. And this type "Dragon" is the class name of the first piece of code provided. I don't see how you can do this, and why you do this.
Could someone explain what's going on, and why it's done this way in the code above?
Thanks a lot, I really appreciate it.