I need to understand behaviour of enum in java example? - java

The first one is enum class
enum coffeeSize{
BIG(8), HUGE(10), OVERWHELMING(16);
private int ounces;
coffeeSize(int ounces ){
this.ounces = ounces;
}
public int getOunces(){
return ounces;
}
}
This is class CoffeeTest1 and main
public class CoffeeTest1 {
coffeeSize size;
public static void main (String args[]) {
CoffeeTest1 drink1 = new CoffeeTest1();
drink1.size = coffeeSize.BIG;
System.out.println(" " + drink1.size.getOunces());
}
}
The below is output
8
My question :
I don't understand the how drink1.size.getounces() manage to output 8. I haven't given constructor coffeeSize(8) object (ex: coffeeSize somex = new coffeeSize(BIG)). I want to know this simple subtle logic behind. Can someone help me understand please?

I dont understand the how "drink1.size.getounces() " manage to output 8.
[...]
I want to know this simple subtle logic behind.
To understand the logic behind this, you can think of your enum as a regular class (which is actually how it is compiled), and
BIG(8)
as an instance of this class similar to
new coffeesize(8);
It should now be clear why drink1.size.getOunces() prints 8: BIG is just an instance of the coffeesize enum, for which you set ounces to 8 when constructing it.

One suggestion: find, learn, and follow the Sun Java coding standards. It'll improve your code's readability.
It outputs 8 because that's the size, in ounces, for BIG coffee size, according to your enum. That's the value that you passed into the BIG constructor.
drink1 is the instance of the class, which has a package visible data member of type coffeeSize named size. Every coffeeSize instance has a method getOunces that returns the integer value that you passed into its constructor.
There's nothing subtle about it.

You will notice the getOunces method is defined on the enum. Enum values can themselves have properties and methods, in Java.
It is implied that CoffeeTest1 has a field that references the enum value.
So drink1 is an instance of that class..
the size property is set to the BIG instance of the enum..
Big has ounces 8.

When you specifies BIG(8) you are creating it passing 8 to its constructor (10 or 16). When you use it coffeeSize.BIG.getOunces() you are invoking its method getOunces. BIG, HUGE and OVERWHELMING are the possible values for a coffeeSize, each one with its own state.

enum Colour {
Black,White,Red,Green,Yellow,Grey
}
public class EnumExample {
public static void main(String[] args) {
Colour colour;
colour = Colour.Black;
System.out.println("Selected "+colour+" Colour");
colour = Colour.Yellow;
System.out.println("Selected "+colour+" Colour");
}
}

Related

How do you use the variables from an enum in another class?

I'm very new to enums and only have an elementary understanding of programming. I recently found out about enums and believe them to be the perfect solution to some of my problems but need some help on how to incorporate them into my code.
I started by creating an enum class. For now I'm working with 7 constants for my enum, and each constant has 1 String variable describing(?) it. How do i code this? And more importantly how do I access this from another class? For instance I want to print the string relating to the constant that is the current value of my enum. Please help. This was really hard for me to describe so hopefully you guys know what I'm trying to ask for.
This is already covered in the official tutorial
public enum Animal {
COW("moo"), // <== calls constructor with any enum specific data
HORSE("neigh"),
SHEEP("ba ba");
private final String noise; // stores the data
private Animal(String noise) { // <== private constuctor
this.noise = noise;
}
public String getNoise() { // <== allow access to the data
return noise;
}
}
Access from another class
Animal animal = Animal.COW;
System.out.println(animal.getNoise());
Enum constants override the toString method so by default it returns the constant name as a string. You can even override it further.
The Javadocs are your friend: http://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#toString--.
You can also often use the enum constant itself directly.
public enum Rainbow {
RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET;
}
Used one way:
Rainbow rainbow = findRainbow();
switch (rainbow) {
case RED:
rosso();
break;
case YELLOW:
giallo();
break;
. . .
case VIOLET:
viola();
break;
}
etc.
Also, enums are classes and you can give them more methods, even override a method differently for each enum constant. Like Java already does with toString.
#shmosel already gave the link to the enum Tutorial.
To declare an enum, follow this synatx Colors("RED", "BLUE")
To access the enum class, declare it as a public class. If the class is in another package, import the class in to the class which is referencing those enums.
sorry my bad for saying to make it static
make it public . so that it can be accessed from any class that the class is imported to .
make somethingn like this from a different class
public class DifferentClass
{
public enum reportType
{
firstReport = 1,
secondReport = 2
}
}
import that class and access it like System.out.println("Report type : " + reportType.firstReport);

What's the point of get and set methods [duplicate]

This question already has answers here:
Set and Get Methods in java?
(16 answers)
Closed 8 years ago.
In my CS class I am just learning about classes and OOP.
So when you create a class you initialize a certain number of private variable.
I know you make them private because if they were public they would be easily changeable and could lead to a lot of bugs.
So we use get and set methods to change the variable. But that once again makes the variables very easy to change right? So whats the point of making them private in the first place?
Some benefits of using getters and setters (known as encapsulation or data-hiding):
1. The fields of a class can be made read-only (by only providing the getter) or write-only (by only providing the setter). This gives the class a total control of who gets to access/modify its fields.
Example:
class EncapsulationExample {
private int readOnly = -1; // this value can only be read, not altered
private int writeOnly = 0; // this value can only be changed, not viewed
public int getReadOnly() {
return readOnly;
}
public int setWriteOnly(int w) {
writeOnly = w;
}
}
2. The users of a class do not need to know how the class actually stores the data. This means data is separated and exists independently from the users thus allowing the code to be more easily modified and maintained. This allows the maintainers to make frequent changes like bug fixes, design and performance enhancements, all while not impacting users.
Furthermore, encapsulated resources are uniformly accessible to each user and have identical behavior independent of the user since this behavior is internally defined in the class.
Example (getting a value):
class EncapsulationExample {
private int value;
public int getValue() {
return value; // return the value
}
}
Now what if I wanted to return twice the value instead? I can just alter my getter and all the code that is using my example doesn't need to change and will get twice the value:
class EncapsulationExample {
private int value;
public int getValue() {
return value*2; // return twice the value
}
}
3. Makes the code cleaner, more readable and easier to comprehend.
Here is an example:
No encapsulation:
class Box {
int widthS; // width of the side
int widthT; // width of the top
// other stuff
}
// ...
Box b = new Box();
int w1 = b.widthS; // Hm... what is widthS again?
int w2 = b.widthT; // Don't mistake the names. I should make sure I use the proper variable here!
With encapsulation:
class Box {
private int widthS; // width of the side
private int widthT; // width of the top
public int getSideWidth() {
return widthS;
}
public int getTopWIdth() {
return widthT;
}
// other stuff
}
// ...
Box b = new Box();
int w1 = b.getSideWidth(); // Ok, this one gives me the width of the side
int w2 = b.getTopWidth(); // and this one gives me the width of the top. No confusion, whew!
Look how much more control you have on which information you are getting and how much clearer this is in the second example. Mind you, this example is trivial and in real-life the classes you would be dealing with a lot of resources being accessed by many different components. Thus, encapsulating the resources makes it clearer which ones we are accessing and in what way (getting or setting).
Here is good SO thread on this topic.
Here is good read on data encapsulation.
As the above comment states, getters and setters encapsulate (i.e. hide) inner details of your class. Thus other classes that interact with yours, do not need to know about the implementation details.
For example, in the simple case you describe, instance variables are exposed via getters and setters. But what if you wanted to change your class so that you no longer used instance variables, but rather you persisted the values to disk. You could make this change to your class without affecting the users of your class.
Keep in mind also that getters and setters need not always be provided. If you do not want your class to provide a way to set or read these properties, then don't. Simply make them private.
get is used to obtain a value for an attribute and set is used to put a value to an attribute
ex:
private int variable;
public int getVariable(){
return variable;
}
public void setVariable(int aux){
variable=aux;
}
In general, is used to encapsulate an attribute.
reference:
Set and Get Methods in java?
Encapsulation or data hiding gives u more control on what values can be set to a field. Here is an example if you don't want a class attribute to have a negative value:
class WithoutGetterSetter {
public int age;
}
class WithGetterSetter {
private int age;
public setAge(int age) {
if(age < 0)
// don't set the value
else
this.age = age;
}
}
public class testEncapslation {
public static void main(String args[]) {
WithoutGetterSetter withoutGetterSetter = new WithoutGetterSetter();
withoutGetterSetter.age = -5;
WithGetterSetter withGetterSetter = new WithGetterSetter();
withGetterSetter.setAge(-5);
}
}
Get and Set methods are preferable to "public" variables because they insulate the users of a class from internal changes.
Supposing you have a variable "StockQty" and you made it public because that seemed like the easiest thing to do.
Later on you get a user requirement to track the history of stock over time. You now need to implement a SetStockQty() method so you can save the old quantity somewhere before setting the new quantity.
Now all the users of your class have to change there code, re-document and re-test.
If you had SetStockQty() method to begin with only you would need to change and test your code.
The second reason is you can have Getters without Setters effectivly making the variable "read only".
Traditionally, they are justified in terms of encapsulation. By providing moderated access to read and write the fields of a class, we supposedly reduce coupling.
In simpler language: by controlling the ways in which other classes can read and change our data, we reduce the ways in which our class's data can change. This means that the connections between classes are reduced, which reduces complexity.
However, the same logic says that getters and setters should generally be avoided unless there's an actual need for them, and there very seldom is such a need. For the most part, a class should "tend to its own knitting" - if there's a calculation to be done on this class's data, it should do it. If a value should be changed, it should do the changing.
For example, consider an object in space. It has a location specified as (x,y,z). We could possibly allow other classes to just set those arbitrarily - this would be horrible, obviously, but it's not obvious that a setter for these would be any better. What you really want is a constructor to set an initial position, and then methods to influence that position - for example, to register an impact or an acceleration. Then you're doing OO programming.
One word, Encapsulation.setters also allow you to control how values are entered into your program. Many new programmers like myself are often confused by this concept. I strongly advice you read this SO question
Being objective: it's all about best pratices!!!
1) IF necessary, expose your attributes with get methods.
2) IF necessary, allow attribute modification (state modification) using set methods;
Have both public get and set methods without treatment is the same as have the attributes public.

Where can i use class methods and instance methods in java

Where can I use an instance method and where is it appropriate to use a class method?
I know the term of class and instance method.
Static methods are class level methods, they are good for utility methods for example Math class in Java. These classes usually take a few inputs work with them and gives desired output(For example Math.pow(4,5)).
Instance methods rather work with the whole object in question. Good example would be almost any class of Java. Still, for example; FileInputStream where read() method reads data from underlying stream.
Example of static method would be
class Math(){
public static long multiply(long a, long b){
return a*b;
}
public static void main(String[]args){
System.out.println(Math.multiply());
}
}
Example of instance method can be
class User(){
private String pass;
private String uname;
public User(String p,String u){
pass=p;
uname=u;
}
public boolean authenticate(){
if("secret".equals(this.pass) && "Grrrr".equals(this.uname){
return true;
}else{
return false;
}
}
public static void main(String[]args){
User u = new User("wrong secret","grrr");
System.out.println(u.authenticate());
}
}
In the second example pay attention to the fact that to use the instance method we must create an object first and then only call the method.
Static methods are conceptually the same as static variables, thus the reasons to use or not use them are similar. They belong to the class, not specific objects of that class. An example from the java API is Math, all the variables are static. Does it make sense to have to create a Math object just to call a single method? Other then the fact that the methods perform some mathematical operation, there is little relation between them. In other words, there are no logical instance variables that would tie the math methods together. As an aside, you can't instantiate Math, so don't waste time trying.
A simple answer to why and when is 'whenever it makes sense". If a method needs to be in a class, but not tied to an object, then it makes sense. If the method is more logically part of an object, then it shouldn't be
Main is static because someone at Sun decided it would be better if the JVM could call main without creating an object first. It probably simplified the design of the JVM.
Hoi,
i can add the following reference:
Excerpt of Joshua Bloch's "Effective Java"
or as Print:
Effective Java (2nd Edition) [Paperback]
The book is really great and anyone wanting to write better code should at least skim it ^^
cu
Here's the link to the Java tutorial, which has a good overview, with examples and code:
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Static methods are suitable for utility classes and to create singletons. Basically in 90% you will avoid static methods.
You cannot overwrite static method using inheritance (polymorphism) - you can only shadow it. Shadowing is anti paten in OOD.
Static methods should not be part of Object Oriented Design - use them only as technical helpers.
This is about understanding representations and their uses.
If you have a class that represents a person, all people may share the same attributes, but their specific attributes will differ. So everyone has a height, but some people are shorter and others taller. To represent a person you need a specific instance that says "my name is bob and im 2m tall", or "my name is sally im 1.9m tall". Your representation of a person depends on the specific instance.
However some things can be represented universally. For example, adding one number to another will always yield the same result, so there's no need for many representations. Hence the Math class has static methods.
In practice, with Java, the jvm will load a class and use it as a "blueprint" for creating instances (all people will share the same attributes, even if their actual values vary), or as the universal definition (for statically declared stuff). For static methods you should be wary of synchronisation (it helps to understand the heap/stack), as well as potential bottlenecks. In distributed applications, the universal definition may be loaded more than once (per jvm).
Ivor Horton has a great example in his book, with a Sphere class. He defines getCount() as a class method, because it gives you the ability to count the number of Spheres you have created, even when there is no Sphere object it returns 0. volume() on the other hand, is an instance method since it calculates the volume of a specific sphere and you have a different volume for every Sphere instance.
public class Sphere {
static final double PI = 3.14; // Class variable that has a fixed value
static int count = 0; // Class variable to count objects
// Instance variables
double radius; // Radius of a sphere
double xCenter; // 3D coordinates
double yCenter; // of the center
double zCenter; // of a sphere
// Class constructor
public Sphere(double theRadius, double x, double y, double z) {
radius = theRadius; // Set the radius
// Set the coordinates of the center
xCenter = x;
yCenter = y;
zCenter = z;
++count; // Update object count
}
// Static method to report the number of objects created
public static int getCount() {
return count; // Return current object count
}
// Instance method to calculate volume
public double volume() {
return 4.0/3.0*PI*radius*radius*radius;
}
}
Try it out with this class:
public class CreateSpheres {
public static void main(String[] args) {
System.out.println(“Number of objects = “ + Sphere.getCount());
Sphere ball = new Sphere(4.0, 0.0, 0.0, 0.0); // Create a sphere
System.out.println(“Number of objects = “ + ball.getCount());
Sphere globe = new Sphere(12.0, 1.0, 1.0, 1.0); // Create a sphere
System.out.println(“Number of objects = “ + Sphere.getCount());
// Output the volume of each sphere
System.out.println(“ball volume = “ + ball.volume());
System.out.println(“globe volume = “ + globe.volume());
}
}
i am giving a brief explanation since i myself am learning about java,but what i have understood in simple language is-
instance methods-dynamic,work with whole objective or purpose of the object in question
class instances-are static,deal with a particular topic concerned with all the objects

How to initialize input fields without writing "if statements"?

I have an enum like
public enum Field {
A, B, C, D, E ....;
private Field(){
}
}
I have a class Panel that takes Field array to initialize the fields:
public class Panel {
TextBox A;
TextBox B;
TextBox C;
TextBox D;
TextBox E;
...
public Panel(Field[] fields){
this.fields = fields;
init();
}
public void initA(){}
public void initB(){}
public void initC(){}
public void initD(){}
public void initE(){}
}
My question is, how can I initialize the fields that given without writing many if statement?
I can't find any solution and I'm now initializing like this:
public void init(){
for(int i = 0 ; i < fields.length; i++){
if(fields[i] == Field.A){
initA();
} else if(fields[i] == Field.B){
initB();
} else if(fields[i] == Field.C){
initC();
} else if(fields[i] == Field.D){
initD();
} else if(fields[i] == Field.E){
initE();
} ....
}
}
Sounds like your design might need to be looked at. A few suggestions:
Add the init method to your enum. So
then you can iterate around the array
of your enums and call the init
method on it, so the enum knows how
to do its own initialization
create a Command object which does
the initialization and create a
Map of your enum as the key and
the Command as the value. Cycle
round the map running the Command
for each enum.
Use reflection - cost wise I wouldn't be too concerned for this, unless your system is after incredibly low latency
For the first bullet, you could change the TextBox to hold a Field type against it e.g.
TextBox A = new TextBox(Field.A);
TextBox B = new TextBox(Field.B);
So if TextBox knows it is A,B,C,D,E then you just need to loop around your Field[] and when it finds its mathing TextBox run the init code (which can be stored against the specific enum instance). Of course you will need to register all your TextBox instances in a data structure somewhere, as you seem very set against using the very widely used reflection API.
In essence there has to be a link between the Field and the TextBox. Java cannot read your mind and know this without you telling it. Well, at least until Google unveil their telepathy API (and that would probably only be for Go...). This can be done based on naming (reflection), hardcoded logic (ifs or switches) or based on state. For the latter this means associating the Field with the TextBox, as I have demonstrated with the Constructor example above.
From a design perspective I'd choose a combination of Factory pattern, Singleton pattern (enum based) and Command pattern. I see a set of commands where each command is specific for a given value. A factory (Singleton) is a common pattern to create such specialized instances. Even though it simply moves the if/switch chain into the factory (but factories are allowed use conditional checks in order to create the instances..).
// the init command
public interface PanelInitializer {
public init(Panel p);
}
// the factory
public enum PanelInitializerFactory {
INSTANCE;
public PanelInitializer create(Field field) {
switch (field) {
case A: return new TypeAInitializer();
case B: return new TypeBInitializer();
case C: return new TypeCInitializer();
//..
}
}
}
I don't think that we can get rid of all conditional checks without using naming conventions and reflection/instantiation or without introducing the constraint, that all initializers share the same code.
Here's a snippet featuring adding the init method to the enum. In each Field's init method you can call one of your different initX() methods. Making the init method abstract gets the compiler to remind you to define your init method for the enum value.
enum Field
{
A{public void init(){initA();}},
B{public void init(){initB();}},
C{public void init(){initC();}},
public abstract void init();
}
You can, as #planetjones mentioned, add an init() method to your enum class. The init method should return a reference to the initialised TextBox of its (enum) type. If you need to pass data to the initialisor you can pass this so that it can retrieve any information it needs.
To get around the problem of finding the variable to assign to, you can either declare an array of TextBoxes
public void init(){
for(int i = 0 ; i < fields.length; i++){
F[i] = fields[i].init(this);
}
}
or assign them after you initialised a temporary array.
public void init(){
TextBox F[5];
for(int i = 0 ; i < fields.length; i++){
F[i] = fields[i].init(this);
}
A = F[0];
B = F[1];
C = F[2];
D = F[3];
E = F[4];
}
Of course you should declare constants instead of using magic numbers.
You could use java reflection to loop through your enum, but you really should look into some way to consolidate all your initN() methods.
Why you current implementation is bad? Only because it looks "ugly"? You can use switch instead of bunch of if:
public void init(){
for(int i = 0 ; i < fields.length; i++){
switch(fields(i)){
case A:
initA();
break
case B:
...
}
}
}
Maybe logic in initA, initB... is very similar? If you have 20 different enums, and 20 different init to run, not much space for improvement...
You could do it, for example, by moving initialization logic to the enum. Have there a method initialize that takes a TextBox as the parameter and initializes it.
BTW you would be better having the TextBox variables in an array.
EDIT
Another option is, what I often is I use an enum as a sort of archetype storage. There I have a method returning an object which matches a certain enum type.
If you do not want to have initialization in enum you could move it to objects you are going to return. There for each particular object you will have a separate initialization.
I am afraid that you are trying to chase the dragon with this one.
Look at it this way. Since the problem of yours is 'conditional', i.e. you have to do a different initialization depending on enum type of a Field, thus at some point you will have to use ifs or switch statement.
Believe there is no magic way around it, how the program should know what you want to do? Even using reflection you will use ifs, etc. to initialize it accordingly.
Your approach is not at all bad if the init methods associated with each TextBox is very different, and the list of Fields is small. Also, if you typically instantiate only one of these Panel instances, the other approaches can actually hurt more than help.
Having said that, consider using a java.util.EnumMap. After that, you have three choices:
register the TextBoxes in some other array as well,
invoke the initA, ... using reflection or
invoke them using some functor construct.
The best choice depends on use case.
Start with this example:
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class FooPanelMain {
public static void main(String[] args) {
FooPanel panel = new FooPanel();
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
class FooPanel extends JPanel {
// fields are dynamically created, so we put them into a map
private Map<PanelField, JLabel> fields = new HashMap<PanelField, JLabel>();
// enum to configure the fields
private enum PanelField {
FIRST("first text"),
SECOND("second text"),
LAST("last text");
private String text;
private PanelField(String text) {
this.text = text;
}
public String getLabelName() {
return text;
}
}
// constructor uses the enum configuration to create the fields
public FooPanel() {
for (PanelField fooPanelField : PanelField.values()) {
createLabel(fooPanelField);
}
}
private void createLabel(PanelField field) {
JLabel label = new JLabel(field.getLabelName());
this.add(label);
fields.put(field, label);
}
}
This example can be easily turned into a abstract solution by defining an interface for PanelField, that is implemented by enums. FooPanel can be used as a base class for Panels.
best u move the init into the enum, just like:
public enum Example{
value1(1),
value2(2),
value3(66);
private final int internalValue;
Example(int value){
this.internalValue = value;
}
public int getInternalValue(){
return this.internalValue;
}
}
Although this is really simple example, you can add any code to the constructor later on and have more complex decisions based on the actual object itself.

Is there any mistake in this Java code?

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 any mistake in this code?
Is "other.yearOfBirth" wrong? My faculty says it is wrong but it works fine for me.
As written, it will work, as you discovered. I suspect that there's a fundamental misunderstanding at play, though.
My psychic powers tell me that your instructor expected code 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 misunderstanding is that you've only created one class-- your main application class. This effectively makes yearOfBirth a sort of hybrid global value that you can access from your main method. In more typical designs, Creature is a class that is completely independent of your main method. In that case, you must only access Creature through its public interface. You would not be able to access its private field directly.
(Note to any pedants out there: Yes, I know I'm simplifying.)
You have to ask your faculty to explain why they think it's wrong (its perhaps a question of style, or even a misunderstanding), so you can learn from it.
Ultimately this person is going to impact your grades. This is an excellent opportunity to have a positive interaction with them. The more involved your teachers are with teaching you personally, the better your opportunity for mastering your subject will be.
If on the other hand when you're told something is wrong you go away privately and ask the general internet community, there is a risk that you'll be told you're right and you'll end up a false sense of superiority over your teachers which will be very counterproductive.
i detect nothing wrong.
the code works, because an instance or class can access private members of other instances of the same class. this is by design.
No, there is no problem at all with it.
Look, it depends on the viewer opinion. But for a given context this code may be just perfect.
For some other context this may not be correct. So it depends of how is going to be used.
Accessing a private member directly from another instance, is correct ( not always desirable though, for instance when you're subclassing ) that's why it is private in first place. You are saying "Hey, this is mine and I know how to use it"
Using the default access modifier for the other two methods, says that your intention is they should not be used by other classes outside the package.
Probably the only thing I would add is to make the class final.
final class Creature
If you want to make it inheritable you probably have to review the get/set for the yearOfBirth attribute, but they way it is is perfect to me.
NOW The most important thing here, is that you understand what each part of your code does, and how it affects its behavior.
You should no code just by luck ( sorry I don't know what's the correct expression for this ) but you should know what you're doing each time you type something, and how do you intend to be used.
I see two "issues," though I hesitate to call them mistakes:
You're explicitly setting Creature c's age as 89, and then rewriting that age with the uninitialized default (!) of Creature d. If this is what you intend to do, then fine, but at the very least you're wasting a few cycles to set a value that you intend to throw out later.
You're possibly violating the JavaBeans naming conventions.
To explain the latter point: a lot of Java libraries and frameworks (notably JSP) rely on JavaBeans to treat the object as a component. I haven't dived deeply into the actual mechanisms used, but from what I've read it relies on Introspection of the JavaBeans class to infer properties and the types of those properties. By overloading your setter setYearOfBirth() to accept both an int and a Creature, you could throw off the Introspection. (See here for a decent introduction to JavaBeans.)
This is not a big deal -- its entirely possible that you won't use this class as a JavaBean, and if you do it's trivial to refactor it so it works. But your teachers would probably prefer something 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 of your access to yearOfBirth comes via the public getter methods, which helps encapsulation, and will prevent the code from breaking if your main method moves to another class. (As Greg D correctly pointed out.)
Also, this has the added benefit of making the intent of your code clear, which becomes more and more important when you start writing code for others to maintain and modify.
It's wrong because you're accessing a private member (you declared private int yearOfBirth) of another object although the class type is the same. You should use the public getter you defined instead: yearOfBirth = other.getYearOfBirth()
yearofBirth is a private int. Therefore the call to other.yearOfBirth would presumably fail...

Categories