Search code examples
javasizenew-operatorrebuild

Do I need to rebuild if a java object I derive from changes in size?


I tried searching for an answer and was unsuccessful. If a class which I derive from which is contained in a jar changes in size, do I need to rebuild my code? By the way, I'm new to java.

I'm pretty sure in C++ the answer is yes. I think a 'new' in C++ consists of a malloc() followed by a call to the constructor. If the size of the class I derive from changes in the binary I'm linking with I would need to recompile my source code so that the compiler knows the new size of the class I'm deriving from otherwise not enough memory will be allocated.

[edited with example]

Bear with me as I'm not that familiar with java. Ignore any syntax errors. Hopefully I'll get the example close enough to get across my point.

public class MyClass extends 3rdPartyClass
{
...
}

public class OneOfMyClasses
{
   public void Foo()
   {
      MyClass mc = new MyClass();  <-- allocation needs to happen here
   }
}

In 3rdParty jar file:

public class 3rdPartyClass
{
   private int int1;
   private int int2;

...
}

Now a change is made in the 3rdPartyClass. They add some more instance members:

public class 3rdPartyClass
{
   private int int1;
   private int int2;
   private int int3;
...
}

There is one more int and thus when the allocation for MyClass happens it needs to change from x bytes to x + sizeof(int) bytes. Is the allocation (malloc?) happening in my code? In C++ the malloc happens in my code and then the call is made to the constructor. Thus my code would have to get recompiled, even though I didn't change anything, such that the correct number of bytes could be allocated. Just wondering how it works in java.

Thanks, Nick


Solution

  • If I understood you correctly, no. If a jar/lib you are using changes the implementation/code you don't have to rebuild your own classes which extend from them.

    If the lib changes public members you have to recompile.

    There are some pitfalls though, I don't remember correctly. But in general I would propose to recompile your code always.

    Java programs use always the standard Java API classes and interfaces which are normal classes in a normal jar. If you distribute a jar of your software compiled with an implementation from one vendor you can let that run against implementations from other vendors. This is quite an important aspect of Java which would not work if memory usage details of one implementation would be used by extending classes. The bytecode compilation is completely free of such stuff.