I’m new to Java and to OOP, so some things below may sound silly, but…
I understand a situation when i have two classes (two different types) and one does whatever it wants with the instance of the other one, like
class A { ... }
class B {
...
public A someMethod() {
return new A;
}
...
}
At the point when B’s method is declaring some code to work with A, the A type is pretty defined and complete and thus one thing can use/make something with another. That all is pretty logical for me at this point.
But I was thinking about the case when a class declaration has a method in it that works with the instance of its own type. How that is possible? I would probably imagine some ‘loop’, but it’s not a loop. How the method can have a code about something that is not ‘complete’ or completely known at the moment when the code is being written.
Sorry if i made some muddled description, I just couldn’t find better words to explain this. Absolutely can’t fit this concept into my head. Could somebody please explain?
UPDATE: i found some snippet that may help you to understand my problem. The code in the class below does not create instance of itself, but it casts the absolutely other object to the its (RectanglePlus’) type…
public class RectanglePlus
implements Relatable {
...
// four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}
...
// a method required to implement
// the Relatable interface
public int isLargerThan(Relatable other) {
RectanglePlus otherRect
= (RectanglePlus)other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
else
return 0;
}
}
Copyright © 2008, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms.
During compilation, this is done by having a multi-pass compiler that first analyzes class and method signatures before dealing with individual statements.
During runtime, class loading and initialization happens when the class is first used and usually before any of its code is executed. Thus, when a method of the class is executed, its
entire structure and code have been initialized.
But you are right that things can get muddled with code that is executed during class initialization, such as static initializer blocks and initial assignments to static fields. If these call methods of the class, such methods are executed within a not-yet fully initialized class context, which can cause unexpected behaviour.