I see two "problems", although I hesitate to call them errors:
You explicitly set the creature's age to 89, and then rewrite that age with the uninitialized default value (!) Of the creature d. If this is what you intend to do, then fine, but at least you spend a few cycles to set the value that you intend to throw out later.
You might be breaking JavaBeans naming conventions.
To explain the last point: many Java libraries and frameworks (especially JSPs) rely on JavaBeans to process an object as a component. I did not go deep into the actual mechanisms used, but from what I read, it relies on the Introspection of the JavaBeans class to determine the properties and types of these properties. By overloading the setYearOfBirth () setter to accept both int and Creature, you can reset Introspection. (See here for a decent introduction to JavaBeans.)
It doesn’t really matter - it’s quite possible that you will not use this class as a JavaBean, and if you do it trivially to reorganize it to work. But your teachers would probably prefer a little cleaner, like the following:
class Creature { private int yearOfBirth=10; public void setYearOfBirth(int year) { yearOfBirth = year; } int getYearOfBirth() { return yearOfBirth; } public static void main(String args[]) { Creature c = new Creature(); c.setYearOfBirth(89); Creature d = new Creature(); c.setYearOfBirth(d.getYearOfBirth()); System.out.println(c.getYearOfBirth()); } }
Now all your access to yearOfBirth comes through the public getter methods, which help to encapsulate and prevent code breaking if your main method moves to another class. (As Greg D. correctly pointed out.)
In addition, it has the added benefit that the purpose of your code becomes clear, which becomes more and more important when you start writing code for others to maintain and change.
rtperson
source share