How JVM decides in which order to initialize classes (invoke <clinit>)? - jvm

From my knowledge, when JVM is loading and generating code for A's clinit, if it encounters an unresolved class B, the compiler will first emit a method call to JVM internal to initialize B, then compile the method call/field use of B normally. So at run-time, B is ensured to be initialized before its field or method is used.
Please correct me if I made any mistake in the above.
Then I don't understand how JVM deal with a situation like below.
public class A {
public static A a = new A(B.b);
public A(B b) {
a = null;
}
public static void main(String[] args) {
System.out.println(a == null);
}
}
public class B {
public static B b = new B(A.a);
public B(A a) {}
}
Could someone explain how these two classes get initialized since they both need the other part to be initialized first? And why the main method in A returns false, since the static field a should be set null in A's constructor?

The second question is easy; the order of operations for the static initialization of A is: B.b is evaluated, new A(B.b) is evaluated (setting a to null), a is assigned new A(B.b). If any other instances of A were created, then a would be null. I think this should be easy to see without detailed knowledge about class initialization.
The first question is a bit more involved. The relevant chapter in the JLS is chapter 12 on execution. The basic idea is this: first a class is loaded, then it is linked, then it is initialized. As part of the linking, the class is prepared; this is when its static fields are created and set to their default values, which is null for references (JLS 12.3.2) -- this happens before static initalization.
So things happen in this order: A is loaded and linked, so a is initialized to null. Then the static initializer runs, so new A(B.b) needs to be evaluated. Now B is loaded and linked, and its static initializer runs, and new B(A.a) is evaluated, and at this point a is null and nothing special happens. Then A's constructor runs and the newly created object is assigned to a.

Related

Why is it not possible to access a static field from a class instance?

In my understanding, a static member belongs to the class rather than to a specific instance of that class. It can be useful if either all instances share this specific characteristic with the exact same value, or if I do not want to create any instances of the class at all.
So, if I have a class Car, and all my cars will always have exactly 4 wheels, I could store the number of wheels as a static member of the class Car rather than as a instance variable of a myCar class instance.
But why should it be not possible in Haxe to access the static variable from a class instance? Doesn't make any sense to me.
class Car
{
public static var noOfWheels:Int = 4;
public static function getNoOfWheels():Int
{
return Car.noOfWheels;
}
}
class Main
{
static function main()
{
myCar = new Car();
trace (myCar.noOfWheels);
trace (myCar.getNoOfWheels());
trace (Type.getClass(myCar).noOfWheels);
}
}
Neither of those traces lead to the desired result. The first and second trace result in an error of the type:
Cannot access static field XY from a class instance
while the third leads to:
Class <Car> has no field noOfWheels
Edit for clarification:
I have several child classes of the Car class, inheriting all its properties. In some cases, like the class ItalianVan, I declare the static variable noOfWheels again, thus overshadowing the original Car.noOfWheels.
class ItalianVan extends Car
{
public static var noOfWheels:Int = 3;
}
Now, if I have an arbitrary car instance, I would like to know how many wheels it has. If I access the Car.noOfWheels, the answer would always be 4 wheels, even if that special car actually was a three-wheeled italian van.
Maybe the answer is: Don't use static variables for stuff like that!
But it isn't obvious to me why.
Seems unnecessary to make noOfWheels an instance variable, if all members of that class have the same number of wheels.
I've never used Haxe but I can see that you are accessing to the myCar variable.
Try this:
trace (Car.noOfWheels);
trace (Car.getNoOfWheels());
When you want to access to a static variable you should use the class name.
To access a static variable from an instance maybe you can add a non static method that returns the result of the static call.

Access class (or object) parent in a correct way using OOP

I need know if this is inside the normal OOP behavior, or if not, what is the most common way to do it (without being specific to a language).
I had a class instanced on the main, called A , which inside had instanced the class B as a variable. When A calls methods inside B, B needs some methods from A for work.
For that, I must bypass the A reference itself via arguments or I must use always the tools specific for the language? OOP give some reference to this or it's out from their scope?
Thank you.
I had a class instanced on the main, called A , which inside had
instanced the class B as a variable. When A calls methods inside B, B
needs some methods from A for work.
The problem here is that, your class A knows too much - it knows how to instantiate another class with its arguments, therefore it becomes also responsible for a factory responsibility. Thus you end up breaking the Single-Responsibility Principle.
So, let's take a look at your current class hierarchy
class A
{
private b;
public void A()
{
b = new B();
}
}
a = new A();
Since you didn't inject an instance of B, this one also becomes bound to the class A.
Since B is tightly-coupled to A, It makes unit-testing very very hard (because you cannot inject a mocked instance of B) i.e you cannot test class A in isolation
It introduces another form of global state, since B comes from global scope
A proper way of doing this would be as (by adhering to the Dependency Injection):
class A
{
private b;
public void A(B bInstance)
{
b = bInstance;
}
}
b = new B();
a = new A(b);

Object References basics

I a new at OO programming and trying to clear up a few things.
When you instatiate a class and create an object, Ive seen the following:
class Program
{
static void Main(string[] args)
{
MyClassA a = new MyClassA();
MyClassA b = a;
MyClassA c = b;
c.DoSomething();
Console.ReadLine();
}
}
public class MyClassA
{
public void DoSomething()
{
Console.WriteLine("I am from Class A");
}
}
This may be a bad example, but the question I am trying to get answered is:
Why is pointing one object reference to another important or why\where is it used? Why not use the object you created in the first place?
This is more Java than generically "object-oriented" -- C++ would be completely different (if you need to "refer" to objects, and change to what object a certain variable "refers" to, you need to use explicit pointers -- references in C++ cannot be "reseated").
Anyway, unconditionally creating synonyms like in your example has no point nor purpose. Much more typical uses would be, for example,
MyClass a = ...whatever...;
MyClass b = ...whatever else...;
MyClass c;
if(something()) {
c = a;
} else {
c = b;
}
c.dosomething();
c.blahblah();
c.andmore();
i.e., having a "synonym" that can refer to one object, or to another one, depending on circumstances, so that following operations can always be coded as being "on the synonym" and they'll be on the "right" object either way (alternatives such as duplicating the whole blocks of "following operations" are, at the very least, very bad and repetitious style, and, e.g. when some of the "following operations" are in other methods and the "synonym" is an instance variable rather than a local variable, can be extremely hard to code, too).
This is just the simplest example, of course. But, do you really need other, more complicated ones?-)

I have a question about OOP .I Need Your help !

Please see the code below :
package bk;
public class A {
protected void methodA() {
System.out.println("Calling the method A !");
}
}
// And I have an another package :
package com;
import bk.A;
public class B extends A {
public void methodB() {
System.out.println("Goi phuong thuc B !");
}
public static void main(String[] args) {
A a = new B();
a.methodA();
}
}
How can I allow a to call methodA()?
Cause methodA() is protected and it can be called within derived classes only. Change it to public if you want to call it like this
Protected methods can only be called from within the class itself, or from derived classes.
The a variable is declared as a variable of type A. Class A itself has no publicly available methodA, so you cannot call it.
Yes, you assign a new B instance to the a variable and the a.methodA() statement is inside the derived B class, but the compiler only sees that a is of type A. It could be any other subclass of A as well, in which case you still wouldn't have access to methodA.
You'll have to tell the compiler that the a variable is actually of type B. Then you will be able to call methodA, because you're calling it from within class B.
B a = new B();
You are trying to access methodA() like it is public. Declaring simply methodA() in the B class is fine, but you cannot do a.methodA().
Conversely if it wasn't a method and simply protected int a;
you could do
a = 1; in class B
but
A a = new A();
a.a = 1;
is not legal
A protected method is visible to inheriting classes, even not part of the same package. A package scope (default) method is not. That is the only difference between protected and package scope.
The theory is that someone extending your class with protected access knows more about what they are doing than someone who is merely using it with public access. They also need more access to your class’s inner workings. Other than that, protected behaves like default package access.

Can a class return an object of itself

Can a class return an object of itself.
In my example I have a class called "Change" which represents a change to the system, and I am wondering if it is in anyway against design principles to return an object of type Change or an ArrayList which is populated with all the recent Change objects.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
In C#, an example might be:
public class Change
{
public int ChangeID { get; set; }
private Change(int changeId)
{
ChangeID = changeId;
LoadFromDatabase();
}
private void LoadFromDatabase()
{
// TODO Perform Database load here.
}
public static Change GetChange(int changeId)
{
return new Change(changeId);
}
}
Yes it can. In fact, that's exactly what a singleton class does. The first time you call its class-level getInstance() method, it constructs an instance of itself and returns that. Then subsequent calls to getInstance() return the already-constructed instance.
Your particular case could use a similar method but you need some way of deciding the list of recent changes. As such it will need to maintain its own list of such changes. You could do this with a static array or list of the changes. Just be certain that the underlying information in the list doesn't disappear - this could happen in C++ (for example) if you maintained pointers to the objects and those objects were freed by your clients.
Less of an issue in an automatic garbage collection environment like Java since the object wouldn't disappear whilst there was still a reference to it.
However, you don't have to use this method. My preference with what you describe would be to have two clases, changelist and change. When you create an instance of the change class, pass a changelist object (null if you don't want it associated with a changelist) with the constructor and add the change to that list before returning it.
Alternatively, have a changelist method which creates a change itself and returns it, remembering the change for its own purposes.
Then you can query the changelist to get recent changes (however you define recent). That would be more flexible since it allows multiple lists.
You could even go overboard and allow a change to be associated with multiple changelists if so desired.
Another reason to return this is so that you can do function chaining:
class foo
{
private int x;
public foo()
{
this.x = 0;
}
public foo Add(int a)
{
this.x += a;
return this;
}
public foo Subtract(int a)
{
this.x -= a;
return this;
}
public int Value
{
get { return this.x; }
}
public static void Main()
{
foo f = new foo();
f.Add(10).Add(20).Subtract(1);
System.Console.WriteLine(f.Value);
}
}
$ ./foo.exe
29
There's a time and a place to do function chaining, and it's not "anytime and everywhere." But, LINQ is a good example of a place that hugely benefits from function chaining.
A class will often return an instance of itself from what is sometimes called a "factory" method. In Java or C++ (etc) this would usually be a public static method, e.g. you would call it directly on the class rather than on an instance of a class.
In your case, in Java, it might look something like this:
List<Change> changes = Change.getRecentChanges();
This assumes that the Change class itself knows how to track changes itself, rather than that job being the responsibility of some other object in the system.
A class can also return an instance of itself in the singleton pattern, where you want to ensure that only one instance of a class exists in the world:
Foo foo = Foo.getInstance();
The fluent interface methods work on the principal of returning an instance of itself, e.g.
StringBuilder sb = new StringBuilder("123");
sb.Append("456").Append("789");
You need to think about what you're trying to model. In your case, I would have a ChangeList class that contains one or more Change objects.
On the other hand, if you were modeling a hierarchical structure where a class can reference other instances of the class, then what you're doing makes sense. E.g. a tree node, which can contain other tree nodes.
Another common scenario is having the class implement a static method which returns an instance of it. That should be used when creating a new instance of the class.
I don't know of any design rule that says that's bad. So if in your model a single change can be composed of multiple changes go for it.