Is there anything wrong with this java code?
class Creature {
class Creature { private int yearOfBirth=10; public void setYearOfBirth(int year) { yearOfBirth = year; } void setYearOfBirth(Creature other) { yearOfBirth = other.yearOfBirth; // is this correct it compiles fine } int getYearOfBirth() { return yearOfBirth; } public static void main(String args[]) { Creature c = new Creature(); c.setYearOfBirth(89); Creature d = new Creature(); c.setYearOfBirth(d); System.out.println(c.yearOfBirth); } }
Is there anything wrong with this code?
Is "other. Yearofbirth" wrong? My teacher said it was wrong, but it was good for me
Solution
As you can see, it works However, I suspect there are fundamental misunderstandings in the game
My psychic ability tells me that your mentor expects the code to be more like the following:
class Creature { private int yearOfBirth=10; public void setYearOfBirth(int year) { yearOfBirth = year; } public void setYearOfBirth(Creature other) { yearOfBirth = other.yearOfBirth; } public int getYearOfBirth() { return yearOfBirth; } } class Program { public static void main(String args[]) { Creature c = new Creature(); c.setYearOfBirth(89); Creature d = new Creature(); c.setYearOfBirth(d); System.out.println(c.yearOfBirth); // This will not compile } }
The misconception is that you only create one class - your main application class This effectively makes yearofbirth a mixed global value that you can access from the main method In a more typical design, a creation is a class that is completely independent of the main method In this case, you can only access the creation through its public interface You will not have direct access to its private fields
(note any student there: Yes, I know I'm simplifying.)